Documentation
¶
Overview ¶
Package tts provides text-to-speech services for converting text responses to audio.
The package defines a common Service interface that abstracts TTS providers, enabling voice AI applications to convert text-only LLM responses to speech.
Architecture ¶
The package provides:
- Service interface for TTS providers
- SynthesisConfig for voice/format configuration
- Voice and AudioFormat types for provider capabilities
- Provider implementations for OpenAI, ElevenLabs, Cartesia and Gemini
Usage ¶
Basic usage with OpenAI TTS:
service := tts.NewOpenAI(os.Getenv("OPENAI_API_KEY"))
reader, err := service.Synthesize(ctx, "Hello world", tts.SynthesisConfig{
Voice: "alloy",
Format: tts.FormatMP3,
})
if err != nil {
log.Fatal(err)
}
defer reader.Close()
// Stream audio to speaker or save to file
io.Copy(audioOutput, reader)
Streaming TTS ¶
For low-latency applications, use StreamingService:
streamer := tts.NewCartesia(os.Getenv("CARTESIA_API_KEY"))
chunks, err := streamer.SynthesizeStream(ctx, "Hello world", tts.DefaultSynthesisConfig())
if err != nil {
log.Fatal(err)
}
for chunk := range chunks {
// Play audio chunk immediately
speaker.Write(chunk.Data)
}
Available Providers ¶
The package includes implementations for:
- OpenAI TTS (tts-1, tts-1-hd and gpt-4o-mini-tts models)
- ElevenLabs
- Cartesia (REST and WebSocket streaming)
- Gemini (speech generation on the Gemini API or Vertex AI; PCM output, Gemini Live's prebuilt voices)
Index ¶
- Constants
- Variables
- func APIKeyFromCredential(c credentials.Credential) string
- func ComputeTTSCost(svc any, text string, latency time.Duration) *types.CostInfo
- func CostInfoToMetaMap(ci *types.CostInfo) map[string]anydeprecated
- func PricingFromSpec(spec ProviderSpec) *base.PricingDescriptor
- func RegisterFactory(providerType string, factory Factory)
- func RegisterPlatforms(providerType string, platforms ...string)
- func RegisteredTypes() []string
- func ResolveCredential(ctx context.Context, providerType string, cfgDir string, ...) (credentials.Credential, error)
- func ResolveCredentialForPlatform(ctx context.Context, providerType string, cfgDir string, ...) (credentials.Credential, error)
- func SynthesizeWithRetry(ctx context.Context, svc Service, text string, config SynthesisConfig, ...) (io.ReadCloser, error)
- func WithCartesiaWSURL(url string) func(*CartesiaService)
- type AudioFormat
- type CartesiaOption
- type CartesiaService
- func (s *CartesiaService) ApplyHTTPTuning(t base.HTTPTuning) error
- func (s *CartesiaService) Close() error
- func (s *CartesiaService) HealthCheck(_ context.Context) error
- func (s *CartesiaService) ImplName() string
- func (s *CartesiaService) Init(_ context.Context) error
- func (s *CartesiaService) ModelName() string
- func (s *CartesiaService) PersonaRubric() string
- func (s *CartesiaService) SpokenText(text string, _ SynthesisConfig) string
- func (s *CartesiaService) SupportedFormats() []AudioFormat
- func (s *CartesiaService) SupportedVoices() []Voice
- func (s *CartesiaService) Synthesize(ctx context.Context, text string, config SynthesisConfig) (io.ReadCloser, error)
- func (s *CartesiaService) SynthesizeStream(ctx context.Context, text string, config SynthesisConfig) (<-chan audio.Chunk, error)
- func (s *CartesiaService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
- func (s *CartesiaService) Type() base.ProviderType
- func (s *CartesiaService) Validate() error
- type ElevenLabsOption
- type ElevenLabsService
- func (s *ElevenLabsService) Close() error
- func (s *ElevenLabsService) HealthCheck(_ context.Context) error
- func (s *ElevenLabsService) ImplName() string
- func (s *ElevenLabsService) Init(_ context.Context) error
- func (s *ElevenLabsService) ModelName() string
- func (s *ElevenLabsService) PersonaRubric() string
- func (s *ElevenLabsService) SetInlineTags(on bool)
- func (s *ElevenLabsService) SpokenText(text string, config SynthesisConfig) string
- func (s *ElevenLabsService) SupportedFormats() []AudioFormat
- func (s *ElevenLabsService) SupportedVoices() []Voice
- func (s *ElevenLabsService) Synthesize(ctx context.Context, text string, config SynthesisConfig) (io.ReadCloser, error)
- func (s *ElevenLabsService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
- func (s *ElevenLabsService) Type() base.ProviderType
- func (s *ElevenLabsService) Validate() error
- type Factory
- type GeminiOption
- type GeminiService
- func (s *GeminiService) ImplName() string
- func (s *GeminiService) ModelName() string
- func (s *GeminiService) SupportedFormats() []AudioFormat
- func (s *GeminiService) SupportedVoices() []Voice
- func (s *GeminiService) Synthesize(ctx context.Context, text string, config SynthesisConfig) (io.ReadCloser, error)
- func (s *GeminiService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
- type OpenAIOption
- type OpenAIService
- func (s *OpenAIService) Close() error
- func (s *OpenAIService) HealthCheck(_ context.Context) error
- func (s *OpenAIService) ImplName() string
- func (s *OpenAIService) Init(_ context.Context) error
- func (s *OpenAIService) ModelName() string
- func (s *OpenAIService) PersonaRubric() string
- func (s *OpenAIService) SetInstructions(on bool)
- func (s *OpenAIService) SpokenText(text string, config SynthesisConfig) string
- func (s *OpenAIService) SupportedFormats() []AudioFormat
- func (s *OpenAIService) SupportedVoices() []Voice
- func (s *OpenAIService) Synthesize(ctx context.Context, text string, config SynthesisConfig) (io.ReadCloser, error)
- func (s *OpenAIService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
- func (s *OpenAIService) Type() base.ProviderType
- func (s *OpenAIService) Validate() error
- type PersonaRubricProvider
- type ProviderSpec
- type RetryConfig
- type Service
- type SpokenTextReporter
- type StreamingService
- type SynthesisConfig
- type SynthesisError
- type Voice
Examples ¶
Constants ¶
const ( // ElevenLabsModelMultilingual is the multilingual v2 model. ElevenLabsModelMultilingual = "eleven_multilingual_v2" // ElevenLabsModelTurbo is the fast turbo v2.5 model. ElevenLabsModelTurbo = "eleven_turbo_v2_5" // ElevenLabsModelEnglish is the English monolingual v1 model. ElevenLabsModelEnglish = "eleven_monolingual_v1" // ElevenLabsModelMultilingualV1 is the older multilingual v1 model. ElevenLabsModelMultilingualV1 = "eleven_multilingual_v1" // ElevenLabsModelV3 is the v3 expressive model that natively consumes // inline characterization tags such as "[whispers]" / "[laughs]". // Markup tags are passed through verbatim in the request body for // any model whose ID starts with "eleven_v3". ElevenLabsModelV3 = "eleven_v3" )
const ( // ModelTTS1 is the OpenAI TTS model optimized for speed. It accepts // the `instructions` field and ignores it, so characterization tags // change nothing in its speech; a service on it can be declared not to // send them (SetInstructions). ModelTTS1 = "tts-1" // ModelTTS1HD is the OpenAI TTS model optimized for quality. Same // behavior as ModelTTS1 for characterization tags. ModelTTS1HD = "tts-1-hd" // ModelGPT4oMiniTTS is the expressive OpenAI TTS model. Honors the // `instructions` request field, which the adapter populates from // markup tags in the input text (see runtime/tts/markup). ModelGPT4oMiniTTS = "gpt-4o-mini-tts" )
const ( VoiceAlloy = "alloy" // Neutral voice. VoiceAsh = "ash" // Ash voice. VoiceBallad = "ballad" // Ballad voice. VoiceCoral = "coral" // Coral voice. VoiceEcho = "echo" // Male voice. VoiceFable = "fable" // British accent. VoiceOnyx = "onyx" // Deep male voice. VoiceNova = "nova" // Female voice. VoiceSage = "sage" // Sage voice. VoiceShimmer = "shimmer" // Soft female voice. VoiceVerse = "verse" // Verse voice. VoiceMarin = "marin" // Recommended for best quality. VoiceCedar = "cedar" // Recommended for best quality. )
OpenAI voices. Ballad, verse, marin and cedar are not available on tts-1 / tts-1-hd.
const (
// CartesiaModelSonic is the Sonic model ID that CartesiaService uses by default.
CartesiaModelSonic = "sonic-3"
)
const ( // GeminiModelFlashTTS is Gemini's flash speech model, the one a service // uses when its configuration names none (a provider spec's model, // base.WithModel, or SynthesisConfig.Model). GeminiModelFlashTTS = "gemini-3.8-flash-tts" )
Variables ¶
var ( // ErrInvalidVoice is returned when the requested voice is not available. ErrInvalidVoice = errors.New("invalid or unsupported voice") // ErrInvalidFormat is returned when the requested format is not supported. ErrInvalidFormat = errors.New("invalid or unsupported audio format") // ErrInvalidModel is returned when the requested model is not available. ErrInvalidModel = errors.New("invalid or unsupported model") // ErrEmptyText is returned when attempting to synthesize empty text. ErrEmptyText = errors.New("text cannot be empty") // ErrSynthesisFailed is returned when TTS synthesis fails. ErrSynthesisFailed = errors.New("speech synthesis failed") // ErrRateLimited is returned when API rate limits are exceeded. ErrRateLimited = errors.New("rate limit exceeded") // ErrQuotaExceeded is returned when account quota is exceeded. ErrQuotaExceeded = errors.New("quota exceeded") ErrServiceUnavailable = errors.New("TTS service unavailable") )
Common TTS errors.
var ( // FormatMP3 is MP3 format (most compatible). FormatMP3 = AudioFormat{ Name: formatMP3, MIMEType: mimeAudioMPEG, SampleRate: sampleRateDefault, BitDepth: 0, Channels: 1, } // FormatOpus is Opus format (best for streaming). FormatOpus = AudioFormat{ Name: "opus", MIMEType: "audio/opus", SampleRate: sampleRateDefault, BitDepth: 0, Channels: 1, } // FormatAAC is AAC format. FormatAAC = AudioFormat{ Name: "aac", MIMEType: "audio/aac", SampleRate: sampleRateDefault, BitDepth: 0, Channels: 1, } // FormatFLAC is FLAC format (lossless). FormatFLAC = AudioFormat{ Name: "flac", MIMEType: "audio/flac", SampleRate: sampleRateDefault, BitDepth: bitDepthDefault, Channels: 1, } // FormatPCM16 is raw 16-bit PCM (for processing). FormatPCM16 = AudioFormat{ Name: formatPCM, MIMEType: "audio/pcm", SampleRate: sampleRateDefault, BitDepth: bitDepthDefault, Channels: 1, } // FormatWAV is WAV format (PCM with header). FormatWAV = AudioFormat{ Name: "wav", MIMEType: "audio/wav", SampleRate: sampleRateDefault, BitDepth: bitDepthDefault, Channels: 1, } )
Common audio formats.
Functions ¶
func APIKeyFromCredential ¶
func APIKeyFromCredential(c credentials.Credential) string
APIKeyFromCredential returns the raw API key from an APIKey credential.
func ComputeTTSCost ¶
ComputeTTSCost computes the cost for a TTS call given the synthesized text and the service. The svc parameter accepts any value; non-pricer implementations (including mock services) return nil cost without error.
The returned CostInfo has:
- Quantities["character"] set to the UTF-8 rune count of text
- TotalCost set to the computed USD amount
- Capability set to "tts"
- ProviderName set from ImplName()
- Latency set to the provided duration
func CostInfoToMetaMap
deprecated
func PricingFromSpec ¶
func PricingFromSpec(spec ProviderSpec) *base.PricingDescriptor
PricingFromSpec extracts an optional pricing override from spec.AdditionalConfig.
func RegisterFactory ¶
RegisterFactory registers a factory for the given provider type. Typically called from per-provider package init().
func RegisterPlatforms ¶ added in v2.21.0
RegisterPlatforms declares the hosting platforms a provider type's factory wires (see base.FactoryRegistry.RegisterPlatforms).
func RegisteredTypes ¶
func RegisteredTypes() []string
RegisteredTypes returns the TTS provider types with a registered factory, sorted. Use it to check a configured type before CreateFromSpec rather than constructing and parsing the error.
func ResolveCredential ¶
func ResolveCredential( ctx context.Context, providerType string, cfgDir string, cred *credentials.CredentialConfig, ) (credentials.Credential, error)
ResolveCredential is a thin wrapper around base.ResolveCredential, kept here for back-compat with callers that resolve TTS-specific credential configs.
func ResolveCredentialForPlatform ¶ added in v2.21.0
func ResolveCredentialForPlatform( ctx context.Context, providerType string, cfgDir string, cred *credentials.CredentialConfig, platform *credentials.PlatformConfig, ) (credentials.Credential, error)
ResolveCredentialForPlatform resolves the credential a spec is built with: the platform's chain for a platform providerType runs on, its own credential otherwise (see base.FactoryRegistry.ResolveCredential).
func SynthesizeWithRetry ¶
func SynthesizeWithRetry( ctx context.Context, svc Service, text string, config SynthesisConfig, cfg RetryConfig, ) (io.ReadCloser, error)
SynthesizeWithRetry calls svc.Synthesize with bounded retry on transient errors. Only errors where SynthesisError.Retryable is true are retried; all others are returned immediately. Uses full jitter backoff to avoid synchronized retries across concurrent callers. A SynthesisError's RetryAfter replaces the backoff; one past MaxDelay is not waited, and the error is returned at once.
func WithCartesiaWSURL ¶
func WithCartesiaWSURL(url string) func(*CartesiaService)
WithCartesiaWSURL sets a custom WebSocket URL.
Types ¶
type AudioFormat ¶
type AudioFormat struct {
// Name is the format identifier ("mp3", "opus", "pcm", "aac", "flac").
Name string
// MIMEType is the content type (e.g., "audio/mpeg").
MIMEType string
// SampleRate is the audio sample rate in Hz.
SampleRate int
// BitDepth is the bits per sample (for PCM formats).
BitDepth int
// Channels is the number of audio channels (1=mono, 2=stereo).
Channels int
}
AudioFormat describes an audio output format.
type CartesiaOption ¶
type CartesiaOption = base.HTTPServiceOption
CartesiaOption configures the Cartesia TTS service. It is a type alias for base.HTTPServiceOption so callers can pass base.WithBaseURL, base.WithClient, base.WithModel, etc. directly. Use WithCartesiaWSURL for Cartesia-specific options.
type CartesiaService ¶
type CartesiaService struct {
*base.Implementation // provides Name, Type, Pricing, Validate, Init, HealthCheck, Close
*base.HTTPServiceFields // APIKey, BaseURL, Model, Client
// contains filtered or unexported fields
}
CartesiaService implements TTS using Cartesia's ultra-low latency API. It supports REST synthesis (Synthesize) and WebSocket streaming (SynthesizeStream).
func NewCartesia ¶
func NewCartesia(apiKey string, opts ...CartesiaOption) *CartesiaService
NewCartesia creates a Cartesia TTS service.
func (*CartesiaService) ApplyHTTPTuning ¶ added in v2.12.0
func (s *CartesiaService) ApplyHTTPTuning(t base.HTTPTuning) error
ApplyHTTPTuning tunes the REST client and keeps the custom headers for the streaming websocket dial. The websocket keeps its own read deadline; the request timeout and transport apply to REST calls only.
func (*CartesiaService) Close ¶
func (s *CartesiaService) Close() error
Close releases resources (no-op for TTS services; HTTP client is shared).
func (*CartesiaService) HealthCheck ¶
func (s *CartesiaService) HealthCheck(_ context.Context) error
HealthCheck reports liveness (no-op for TTS services).
func (*CartesiaService) ImplName ¶
func (s *CartesiaService) ImplName() string
ImplName returns the implementation name for cost tracking.
func (*CartesiaService) Init ¶
func (s *CartesiaService) Init(_ context.Context) error
Init performs asynchronous setup (no-op for TTS services).
func (*CartesiaService) ModelName ¶
func (s *CartesiaService) ModelName() string
ModelName returns the configured model name for cost tracking.
func (*CartesiaService) PersonaRubric ¶
func (s *CartesiaService) PersonaRubric() string
PersonaRubric implements PersonaRubricProvider. Returns the emotion-only rubric: the adapter maps only emotion tags (excited, content, sad, angry) onto Cartesia's generation config, so only those are advertised. Other tags (e.g. whispers, pause) are dropped from the request, so the rubric omits them.
func (*CartesiaService) SpokenText ¶
func (s *CartesiaService) SpokenText(text string, _ SynthesisConfig) string
SpokenText reports the text Cartesia will actually speak for the given input: emotion tags become generation config, so the spoken transcript is the text with tags removed. Implements tts.SpokenTextReporter.
func (*CartesiaService) SupportedFormats ¶
func (s *CartesiaService) SupportedFormats() []AudioFormat
SupportedFormats returns audio formats supported by Cartesia.
func (*CartesiaService) SupportedVoices ¶
func (s *CartesiaService) SupportedVoices() []Voice
SupportedVoices returns a sample of available Cartesia voices.
func (*CartesiaService) Synthesize ¶
func (s *CartesiaService) Synthesize( ctx context.Context, text string, config SynthesisConfig, ) (io.ReadCloser, error)
Synthesize converts text to audio using Cartesia's REST API. For streaming output, use SynthesizeStream instead.
func (*CartesiaService) SynthesizeStream ¶
func (s *CartesiaService) SynthesizeStream( ctx context.Context, text string, config SynthesisConfig, ) (<-chan audio.Chunk, error)
SynthesizeStream converts text to audio with streaming output via WebSocket. Audio chunks arrive on the returned channel as they are generated.
func (*CartesiaService) SynthesizeTTS ¶
func (s *CartesiaService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
SynthesizeTTS implements base.TTSProvider for CartesiaService.
func (*CartesiaService) Type ¶
func (s *CartesiaService) Type() base.ProviderType
Type returns ProviderTypeTTS for CartesiaService.
func (*CartesiaService) Validate ¶
func (s *CartesiaService) Validate() error
Validate performs synchronous config validation (no-op for TTS services).
type ElevenLabsOption ¶
type ElevenLabsOption = base.HTTPServiceOption
ElevenLabsOption configures the ElevenLabs TTS service. It is a type alias for base.HTTPServiceOption so callers can pass base.WithBaseURL, base.WithClient, base.WithModel, etc. directly.
type ElevenLabsService ¶
type ElevenLabsService struct {
*base.Implementation // provides Name, Type, Pricing, Validate, Init, HealthCheck, Close
*base.HTTPServiceFields // APIKey, BaseURL, Model, Client
// contains filtered or unexported fields
}
ElevenLabsService implements TTS using ElevenLabs' API. ElevenLabs specializes in high-quality voice cloning and natural-sounding speech.
func NewElevenLabs ¶
func NewElevenLabs(apiKey string, opts ...ElevenLabsOption) *ElevenLabsService
NewElevenLabs creates an ElevenLabs TTS service.
func (*ElevenLabsService) Close ¶
func (s *ElevenLabsService) Close() error
Close releases resources (no-op for TTS services; HTTP client is shared).
func (*ElevenLabsService) HealthCheck ¶
func (s *ElevenLabsService) HealthCheck(_ context.Context) error
HealthCheck reports liveness (no-op for TTS services).
func (*ElevenLabsService) ImplName ¶
func (s *ElevenLabsService) ImplName() string
ImplName returns the implementation name for cost tracking.
func (*ElevenLabsService) Init ¶
func (s *ElevenLabsService) Init(_ context.Context) error
Init performs asynchronous setup (no-op for TTS services).
func (*ElevenLabsService) ModelName ¶
func (s *ElevenLabsService) ModelName() string
ModelName returns the configured model name for cost tracking.
func (*ElevenLabsService) PersonaRubric ¶
func (s *ElevenLabsService) PersonaRubric() string
PersonaRubric implements PersonaRubricProvider. Returns the full markup rubric on a model that takes inline tags (SetInlineTags, else v3-class models); older models (v1, v2, turbo) speak the brackets literally, so we return the empty string and the persona prompt is left untouched.
func (*ElevenLabsService) SetInlineTags ¶ added in v2.22.0
func (s *ElevenLabsService) SetInlineTags(on bool)
SetInlineTags declares whether the service's configured model takes inline markup tags such as "[whispers]". On, the tags are sent as written and PersonaRubric offers the markup rubric; off, they are stripped from the text and no rubric is offered. It wins over the model ID, which otherwise decides (eleven_v3* takes tags). A request for another model (SynthesisConfig.Model) is decided by that model's ID. The declarative form is additional_config.inline_tags.
func (*ElevenLabsService) SpokenText ¶
func (s *ElevenLabsService) SpokenText(text string, config SynthesisConfig) string
SpokenText reports the text ElevenLabs will actually speak for the given input, after markup lowering: a model that takes inline tags (SetInlineTags, else eleven_v3) keeps them, other models strip them. Implements tts.SpokenTextReporter.
func (*ElevenLabsService) SupportedFormats ¶
func (s *ElevenLabsService) SupportedFormats() []AudioFormat
SupportedFormats returns audio formats supported by ElevenLabs.
func (*ElevenLabsService) SupportedVoices ¶
func (s *ElevenLabsService) SupportedVoices() []Voice
SupportedVoices returns a sample of available ElevenLabs voices. Note: ElevenLabs has many more voices including custom cloned voices. Use the ElevenLabs API to get a complete list of available voices.
func (*ElevenLabsService) Synthesize ¶
func (s *ElevenLabsService) Synthesize( ctx context.Context, text string, config SynthesisConfig, ) (io.ReadCloser, error)
Synthesize converts text to audio using ElevenLabs' TTS API.
func (*ElevenLabsService) SynthesizeTTS ¶
func (s *ElevenLabsService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
SynthesizeTTS implements base.TTSProvider for ElevenLabsService.
func (*ElevenLabsService) Type ¶
func (s *ElevenLabsService) Type() base.ProviderType
Type returns ProviderTypeTTS for ElevenLabsService.
func (*ElevenLabsService) Validate ¶
func (s *ElevenLabsService) Validate() error
Validate performs synchronous config validation (no-op for TTS services).
type Factory ¶
Factory builds a Service from a spec. Per-provider packages register one of these via init() so this package never needs to import them.
type GeminiOption ¶ added in v2.22.0
type GeminiOption = base.HTTPServiceOption
GeminiOption configures the Gemini TTS service. It is base.HTTPServiceOption, so base.WithBaseURL, base.WithClient and base.WithModel apply.
type GeminiService ¶ added in v2.22.0
type GeminiService struct {
*base.Implementation // provides Name, Type, Pricing, Validate, Init, HealthCheck, Close
*base.HTTPServiceFields // APIKey, BaseURL, Model, Client
// contains filtered or unexported fields
}
GeminiService implements TTS with Gemini's speech generation: a generateContent call with AUDIO output, on the Gemini API (API key) or on Vertex AI (platform credential). It returns 16-bit mono PCM.
func NewGemini ¶ added in v2.22.0
func NewGemini(apiKey string, opts ...GeminiOption) *GeminiService
NewGemini creates a Gemini TTS service on the Gemini API, authenticated with apiKey (sent in the x-goog-api-key header).
func NewGeminiOnVertex ¶ added in v2.22.0
func NewGeminiOnVertex( cred credentials.Credential, project, location string, opts ...GeminiOption, ) *GeminiService
NewGeminiOnVertex creates a Gemini TTS service on Vertex AI in a project and location. Every request carries cred (a GCP OAuth token) and no API key. base.WithBaseURL replaces the location's Google publisher models URL. A client passed with base.WithClient keeps its own transport, wrapped so the credential is still applied to every request.
func (*GeminiService) ImplName ¶ added in v2.22.0
func (s *GeminiService) ImplName() string
ImplName returns the implementation name for cost tracking.
func (*GeminiService) ModelName ¶ added in v2.22.0
func (s *GeminiService) ModelName() string
ModelName returns the configured model name for cost tracking.
func (*GeminiService) SupportedFormats ¶ added in v2.22.0
func (s *GeminiService) SupportedFormats() []AudioFormat
SupportedFormats returns the one format Gemini TTS produces: 24 kHz 16-bit mono PCM (Synthesize resamples it to Format.SampleRate on request).
func (*GeminiService) SupportedVoices ¶ added in v2.22.0
func (s *GeminiService) SupportedVoices() []Voice
SupportedVoices returns Gemini's prebuilt voices. The ID is the name a request (and a Gemini Live session's metadata["voice"]) uses.
func (*GeminiService) Synthesize ¶ added in v2.22.0
func (s *GeminiService) Synthesize(ctx context.Context, text string, config SynthesisConfig) (io.ReadCloser, error)
Synthesize converts text to 16-bit mono PCM. The reply's audio (a WAV or raw PCM, depending on the model) is unwrapped to its samples and returned at config.Format.SampleRate, or at 24 kHz when that is unset.
func (*GeminiService) SynthesizeTTS ¶ added in v2.22.0
func (s *GeminiService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
SynthesizeTTS implements base.TTSProvider for GeminiService. Gemini TTS produces PCM only, so that is the default format.
type OpenAIOption ¶
type OpenAIOption = base.HTTPServiceOption
OpenAIOption configures the OpenAI TTS service. It is a type alias for base.HTTPServiceOption so callers can pass base.WithBaseURL, base.WithClient, base.WithModel, etc. directly.
type OpenAIService ¶
type OpenAIService struct {
*base.Implementation // provides Name, Type, Pricing, Validate, Init, HealthCheck, Close
*base.HTTPServiceFields // APIKey, BaseURL, Model, Client
// contains filtered or unexported fields
}
OpenAIService implements TTS using OpenAI's text-to-speech API.
func NewOpenAI ¶
func NewOpenAI(apiKey string, opts ...OpenAIOption) *OpenAIService
NewOpenAI creates an OpenAI TTS service.
func (*OpenAIService) Close ¶
func (s *OpenAIService) Close() error
Close releases resources (no-op for TTS services; HTTP client is shared).
func (*OpenAIService) HealthCheck ¶
func (s *OpenAIService) HealthCheck(_ context.Context) error
HealthCheck reports liveness (no-op for TTS services).
func (*OpenAIService) ImplName ¶
func (s *OpenAIService) ImplName() string
ImplName returns the implementation name for cost tracking.
func (*OpenAIService) Init ¶
func (s *OpenAIService) Init(_ context.Context) error
Init performs asynchronous setup (no-op for TTS services).
func (*OpenAIService) ModelName ¶
func (s *OpenAIService) ModelName() string
ModelName returns the configured model name for cost tracking.
func (*OpenAIService) PersonaRubric ¶
func (s *OpenAIService) PersonaRubric() string
PersonaRubric implements PersonaRubricProvider. Returns the full markup rubric, or the empty string on a service declared not to send instructions (SetInstructions), whose tags would only waste persona tokens.
func (*OpenAIService) SetInstructions ¶ added in v2.22.0
func (s *OpenAIService) SetInstructions(on bool)
SetInstructions declares whether the service's model honors the request's instructions field, which carries the directives of the markup tags in the text (see runtime/tts/markup). It is on by default: the API takes the field on every speech model, and tts-1 and tts-1-hd ignore it. Off, the tags are stripped from the spoken text, their directives are not sent, and PersonaRubric offers no rubric, so a persona spends no tokens on tags the model cannot act on. The declarative form is additional_config.instructions.
func (*OpenAIService) SpokenText ¶
func (s *OpenAIService) SpokenText(text string, config SynthesisConfig) string
SpokenText reports the text OpenAI will actually speak for the given input, after markup lowering: the bracket tags become the `instructions` field, or are dropped on a service that sends none, so the spoken text is the stripped remainder. Implements tts.SpokenTextReporter.
func (*OpenAIService) SupportedFormats ¶
func (s *OpenAIService) SupportedFormats() []AudioFormat
SupportedFormats returns audio formats supported by OpenAI TTS.
func (*OpenAIService) SupportedVoices ¶
func (s *OpenAIService) SupportedVoices() []Voice
SupportedVoices returns the OpenAI voices. tts-1 and tts-1-hd lack ballad, verse, marin and cedar, which their descriptions say.
func (*OpenAIService) Synthesize ¶
func (s *OpenAIService) Synthesize( ctx context.Context, text string, config SynthesisConfig, ) (io.ReadCloser, error)
Synthesize converts text to audio using OpenAI's TTS API.
func (*OpenAIService) SynthesizeTTS ¶
func (s *OpenAIService) SynthesizeTTS(ctx context.Context, req base.TTSRequest) (base.TTSStream, error)
SynthesizeTTS implements base.TTSProvider for OpenAIService. It bridges the base.TTSRequest to the existing Synthesize method and wraps the response in a streaming ttsStream.
func (*OpenAIService) Type ¶
func (s *OpenAIService) Type() base.ProviderType
Type returns ProviderTypeTTS for all TTS services.
func (*OpenAIService) Validate ¶
func (s *OpenAIService) Validate() error
Validate performs synchronous config validation (no-op for TTS services).
type PersonaRubricProvider ¶
type PersonaRubricProvider interface {
PersonaRubric() string
}
PersonaRubricProvider is an optional extension interface that TTS adapters implement to advertise the bracket-tag rubric an upstream persona / script should splice into its system prompt. Implementations return the empty string when the configured model cannot consume characterization markup. Callers must treat the empty string as "do not inject any rubric", so that persona tokens are not spent on tags that would be silently dropped.
See github.com/AltairaLabs/PromptKit/runtime/v2/tts/markup for the canonical rubric strings each adapter may return.
type ProviderSpec ¶
type ProviderSpec = base.CapabilitySpec
ProviderSpec is the runtime form of a TTS-provider declaration. It is a type alias for base.CapabilitySpec so the field shape is shared with STT, embedding, and image factories without code duplication.
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the total number of attempts including the initial
// call. 3 means "initial + up to 2 retries". Values < 1 are
// treated as 1 (no retry).
MaxAttempts int
// InitialDelay is the base backoff before the first retry.
InitialDelay time.Duration
// MaxDelay caps the per-attempt backoff.
MaxDelay time.Duration
}
RetryConfig configures bounded retry for TTS synthesis calls. TTS calls are one-shot and idempotent, so retry has no content-duplication risk.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns sensible defaults for TTS retry.
type Service ¶
type Service interface {
// Name returns the provider identifier (for logging/debugging).
Name() string
// Synthesize converts text to audio.
// Returns a reader for streaming audio data.
// The caller is responsible for closing the reader.
Synthesize(ctx context.Context, text string, config SynthesisConfig) (io.ReadCloser, error)
// SupportedVoices returns available voices for this provider.
SupportedVoices() []Voice
// SupportedFormats returns supported audio output formats.
SupportedFormats() []AudioFormat
}
Service converts text to speech audio. This interface abstracts different TTS providers (OpenAI, ElevenLabs, etc.) enabling voice AI applications to use any provider interchangeably.
func CreateFromSpec ¶
func CreateFromSpec(spec ProviderSpec) (Service, error)
CreateFromSpec returns a Service implementation for the given spec.
type SpokenTextReporter ¶
type SpokenTextReporter interface {
// SpokenText returns the text that would actually be spoken for the given
// input and config, after markup lowering.
SpokenText(text string, config SynthesisConfig) string
}
SpokenTextReporter is an optional Service extension: given the input text and config, it returns the exact text that will be submitted to the synthesis engine after PromptKit's bracket-tag markup is lowered. The result is provider- and model-specific (e.g. OpenAI gpt-4o-mini-tts moves tags to `instructions`, so the spoken text is the stripped remainder; ElevenLabs v3 keeps inline tags). The lowering is pure, so this reports the value without synthesizing. Returns "" when unknown, letting consumers fall back to the LLM text.
type StreamingService ¶
type StreamingService interface {
Service
// SynthesizeStream converts text to audio with streaming output.
// Returns a channel that receives audio chunks as they're generated.
// The channel is closed when synthesis completes or an error occurs.
SynthesizeStream(ctx context.Context, text string, config SynthesisConfig) (<-chan audio.Chunk, error)
}
StreamingService extends Service with streaming synthesis capabilities. Streaming TTS provides lower latency by returning audio chunks as they're generated.
type SynthesisConfig ¶
type SynthesisConfig struct {
// Voice is the voice ID to use for synthesis.
// Available voices vary by provider - use SupportedVoices() to list options.
Voice string
// Format is the output audio format. If the zero value, the provider uses its
// default format (MP3 for OpenAI).
Format AudioFormat
// Speed is the speech rate multiplier (default 1.0).
// Only OpenAIService reads it.
Speed float64
// Pitch adjusts the voice pitch in semitones (default 0), for a custom
// Service whose API supports pitch. The built-in services ignore it: the
// OpenAI speech API, the ElevenLabs text-to-speech API (including its
// voice_settings) and the Cartesia TTS API (including generation_config)
// have no pitch parameter.
Pitch float64
// Language is the language code for synthesis (e.g., "en-US").
// Only CartesiaService sends it.
Language string
// Model is the TTS model to use (provider-specific). If empty, the service's
// configured model is used. For OpenAI: ModelTTS1, ModelTTS1HD or ModelGPT4oMiniTTS.
Model string
// PreviousText and NextText are the text spoken just before and just
// after this text, when it is one segment of a longer reply synthesized a
// segment at a time: a service can use them to keep the speech's prosody
// continuous across segments. Empty when there is none, or it is not known
// yet. Only ElevenLabsService sends them (previous_text and next_text).
PreviousText string
NextText string
}
SynthesisConfig configures text-to-speech synthesis.
func DefaultSynthesisConfig ¶
func DefaultSynthesisConfig() SynthesisConfig
DefaultSynthesisConfig returns sensible defaults for synthesis.
Example ¶
ExampleDefaultSynthesisConfig shows the sensible defaults returned for text-to-speech synthesis: alloy voice, MP3 output, normal speed and pitch. No network access or API key is required to build the config.
config := DefaultSynthesisConfig()
fmt.Printf("voice=%s format=%s speed=%.1f pitch=%.0f\n",
config.Voice, config.Format.Name, config.Speed, config.Pitch)
Output: voice=alloy format=mp3 speed=1.0 pitch=0
type SynthesisError ¶
type SynthesisError struct {
// Provider is the TTS provider that returned the error.
Provider string
// Code is the provider-specific error code.
Code string
// Message is the error message.
Message string
// Cause is the underlying error (if any).
Cause error
// Retryable indicates if the error is transient and retry may succeed.
Retryable bool
// RetryAfter is how long the provider asked the caller to wait before
// trying again (its Retry-After header), or zero when it did not say.
// SynthesizeWithRetry waits this long instead of its own backoff.
RetryAfter time.Duration
}
SynthesisError provides detailed error information from TTS providers.
func NewSynthesisError ¶
func NewSynthesisError(provider, code, message string, cause error, retryable bool) *SynthesisError
NewSynthesisError creates a new SynthesisError.
func (*SynthesisError) Error ¶
func (e *SynthesisError) Error() string
Error implements the error interface.
func (*SynthesisError) Unwrap ¶
func (e *SynthesisError) Unwrap() error
Unwrap returns the underlying error.
type Voice ¶
type Voice struct {
// ID is the provider-specific voice identifier.
ID string
// Name is a human-readable voice name.
Name string
// Language is the primary language code (e.g., "en", "es", "fr").
Language string
// Gender is the voice gender ("male", "female", "neutral").
Gender string
// Description provides additional voice characteristics.
Description string
// Preview is a URL to a voice sample (if available).
Preview string
}
Voice describes a TTS voice available from a provider.