Documentation
¶
Overview ¶
Package soniox provides Soniox's real-time speech services over its WebSocket APIs.
Speech-to-text (NewSTT) streams tokens, each marked final or provisional, and signals an endpoint with a special "<end>" token; the service surfaces provisional text as interims and the utterance up to the endpoint as a finalized transcript. The pipeline decides where the user's turn ends unless Config.VADForceTurnEndpoint is off, in which case the endpoint does.
Text-to-speech (NewTTS) holds one connection open for the call and speaks each turn on a stream of its own on it, sending the turn's sentences to the stream as they are ready and streaming the audio chunks downstream as Soniox generates them, reporting per-word timing from the character timestamps it returns.
Index ¶
- type Config
- type Context
- type ContextGeneralItem
- type ContextTranslationTerm
- type ExpressionAdapter
- func (ExpressionAdapter) Capabilities() *expressive.ExpressionCapabilities
- func (ExpressionAdapter) FormatEnd(delivery []string) string
- func (ExpressionAdapter) FormatPause(durationMS int) string
- func (ExpressionAdapter) FormatSound(name string) string
- func (ExpressionAdapter) FormatText(text string, delivery, previousDelivery []string) string
- type STTService
- type Settings
- type TTSConfig
- type TTSService
- type TTSSettings
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// APIKey is the Soniox API key, sent on the WebSocket handshake. Required.
APIKey string `validate:"required"`
// URL overrides the real-time endpoint; empty uses the hosted endpoint.
URL string
// Model is the transcription model; empty uses a current default.
Model string
// Language hints the spoken language; the zero value lets Soniox auto-detect.
// It becomes the one language hint, unless LanguageHints are given.
Language language.Language
// LanguageHints are the languages to expect, for a conversation in more
// than one. When given, they are the hints and Language is not added.
LanguageHints []language.Language
// SampleRate is the input audio sample rate; 0 uses the transport's rate.
SampleRate int
// VADForceTurnEndpoint says who decides where a user turn ends; nil means
// true.
//
// When true, the pipeline's user turn strategies decide, and a VAD stop
// asks Soniox to finalize so the transcript arrives sooner. Soniox's
// endpoint detection still ends the transcript of speech the VAD missed,
// but never the turn.
//
// When false, Soniox's endpoint detection decides. The service proposes a
// turn start on the pipeline's VAD hearing the user start, when there is a
// VAD, or on the first token otherwise, and a turn stop on the endpoint,
// behind its transcript. It recommends the external user turn strategies,
// which resolve those proposals.
VADForceTurnEndpoint *bool
// ShouldInterrupt barges in when the user starts speaking; nil enables
// it. It only applies with VADForceTurnEndpoint off, and is passed along
// to the user turn strategies the service recommends, which own the
// interruption; strategies the application configures itself override the
// recommendation and this setting with it.
ShouldInterrupt *bool
// LanguageHintsStrict confines recognition to the hinted language; nil omits
// it and lets Soniox decide.
LanguageHintsStrict *bool
// Context primes the model with what the conversation is about, for the
// models that take it; nil omits it.
Context *Context
// EnableSpeakerDiarization labels speakers in the transcript; nil omits it.
EnableSpeakerDiarization *bool
// EnableLanguageIdentification reports the language of each token; nil omits
// it.
EnableLanguageIdentification *bool
// MaxEndpointDelayMs bounds how long Soniox waits before ending a turn; nil
// omits it.
MaxEndpointDelayMs *int
// EndpointSensitivity tunes how readily Soniox calls a turn ended; nil omits
// it.
EndpointSensitivity *float64
// EndpointLatencyAdjustmentLevel trades endpoint latency against accuracy;
// nil omits it.
EndpointLatencyAdjustmentLevel *int
// ClientReferenceID labels the session in Soniox's own records; empty omits
// it.
ClientReferenceID string
// EnableReconnect reconnects a dropped connection to the same Soniox
// stream, keeping the transcript and the audio sent around the drop. Soniox
// bills the up to 20 s a dropped stream waits for the reconnect. Nil leaves
// it off.
EnableReconnect *bool
// EnableAgentTextInput sends each completed bot reply to Soniox as agent
// text, so words the bot said (a product name, say) are recognized when
// the user says them. It only takes effect on models that support agent
// text input (stt-rt-v6 and later), and stays off for older ones. Agent
// text is billed as input text tokens. Nil leaves it on.
EnableAgentTextInput *bool
// EnableEchoCancellation sends the bot's speech to Soniox as agent text
// while it plays, which also lets Soniox cancel the bot's echo in the
// user's audio. It implies EnableAgentTextInput, and likewise only takes
// effect on models that support it. It needs a TTS service that reports
// word timestamps. Nil leaves it off.
EnableEchoCancellation *bool
// AgentTextLeadMs is how far ahead of playback each of the bot's words is
// sent, in milliseconds. Soniox places agent text where it sits among the
// audio frames and wants it a little before the caller hears it; 500 to
// 1000 is the documented range, and 0 sends each word as it starts
// playing. Only used with EnableEchoCancellation, for a TTS service that
// reports word timestamps. Nil uses 700.
AgentTextLeadMs *int `validate:"omitempty,min=0"`
// SpeakerFormat formats each diarized speaker run: {speaker} is Soniox's
// speaker label, {text} the transcript text, and {speaker_number} the
// speaker's order of first appearance in the session (1, 2, ...), e.g.
// "{speaker}: {text}". Empty leaves the text as it is. It is applied
// locally, so changing it does not reopen the session.
SpeakerFormat string
// TTFSP99 overrides the measured transcript latency the turn strategies
// size their wait by; nil uses stt.SonioxTTFSP99, and zero means no wait.
TTFSP99 *time.Duration
// Websocket configures the connection: whether and how it reconnects, and
// how long it waits on a peer that has stopped answering.
Websocket wsservice.Options
}
Config configures the Soniox STT service.
type Context ¶ added in v0.1.0
type Context struct {
// General is structured context as key-value pairs.
General []ContextGeneralItem `json:"general,omitempty"`
// Text is free-form context.
Text string `json:"text,omitempty"`
// Terms are words the model should expect to hear.
Terms []string `json:"terms,omitempty"`
// TranslationTerms fix how particular terms are translated.
TranslationTerms []ContextTranslationTerm `json:"translation_terms,omitempty"`
}
Context primes the model with what the conversation is about, for the models that take it.
type ContextGeneralItem ¶ added in v0.1.0
ContextGeneralItem is one key-value pair of structured context.
type ContextTranslationTerm ¶ added in v0.1.0
ContextTranslationTerm maps an ambiguous or domain-specific term onto the translation it should take.
type ExpressionAdapter ¶ added in v1.0.0
type ExpressionAdapter struct {
expressive.BaseExpressionAdapter
}
ExpressionAdapter formats expression tags as Soniox TTS audio tags.
Delivery and sounds are both tags, such as [excited] or [laughs], from Soniox's emotion and tone reference; Soniox may read a tag outside it aloud. A tag lasts past the sentence it is sent in, so a return to the voice's baseline within a sentence writes [neutral], and so does the end of a sentence spoken in a delivery. Slow and fast are written as [slowly] and [quickly], emphasis as *word*, and a pause as a pause or a long pause, which is approximate.
func (ExpressionAdapter) Capabilities ¶ added in v1.0.0
func (ExpressionAdapter) Capabilities() *expressive.ExpressionCapabilities
Capabilities implements expressive.ExpressionAdapter: Soniox's tags, emphasis and approximate pauses.
func (ExpressionAdapter) FormatEnd ¶ added in v1.0.0
func (ExpressionAdapter) FormatEnd(delivery []string) string
FormatEnd implements expressive.ExpressionAdapter: it sets the delivery back after a sentence spoken in one.
func (ExpressionAdapter) FormatPause ¶ added in v1.0.0
func (ExpressionAdapter) FormatPause(durationMS int) string
FormatPause implements expressive.ExpressionAdapter: a pause under a second, otherwise a long pause, set apart like a sound.
func (ExpressionAdapter) FormatSound ¶ added in v1.0.0
func (ExpressionAdapter) FormatSound(name string) string
FormatSound implements expressive.ExpressionAdapter: a tag, set apart so its timestamps time it as a word of its own.
func (ExpressionAdapter) FormatText ¶ added in v1.0.0
func (ExpressionAdapter) FormatText(text string, delivery, previousDelivery []string) string
FormatText implements expressive.ExpressionAdapter: it prefixes tags where the delivery changes, and marks emphasis.
type STTService ¶ added in v1.0.0
type STTService struct {
*stt.StreamService
// contains filtered or unexported fields
}
STTService is the Soniox speech-to-text service NewSTT builds.
func (*STTService) Cleanup ¶ added in v1.2.0
func (s *STTService) Cleanup(ctx context.Context) error
Cleanup stops observing the bot's speech and releases the service's resources.
func (*STTService) ProcessFrame ¶ added in v1.2.0
func (s *STTService) ProcessFrame(ctx context.Context, f frames.Frame, dir processor.Direction) error
ProcessFrame processes a frame as the service does, then, when Soniox decides the turns, opens the user's turn on the pipeline's VAD hearing the user start. That is the fastest signal there is: the first token arrives a network round trip and the model's latency later, and opens the turn only when there is no VAD.
type Settings ¶ added in v0.1.0
type Settings struct {
settings.STT
// LanguageHints are the languages to expect, each named the way Soniox
// names it when a session opens. An update giving a language and no hints
// replaces the hints with that language, since the hints are what Soniox
// reads.
LanguageHints settings.Opt[[]string] `settings:"language_hints"`
// LanguageHintsStrict confines recognition to the languages hinted.
LanguageHintsStrict settings.Opt[bool] `settings:"language_hints_strict"`
// Context primes the model with what the conversation is about.
Context settings.Opt[Context] `settings:"context"`
// EnableSpeakerDiarization labels speakers in the transcript.
EnableSpeakerDiarization settings.Opt[bool] `settings:"enable_speaker_diarization"`
// EnableLanguageIdentification reports the language of each token.
EnableLanguageIdentification settings.Opt[bool] `settings:"enable_language_identification"`
// MaxEndpointDelayMs bounds how long Soniox waits before ending a turn.
MaxEndpointDelayMs settings.Opt[int] `settings:"max_endpoint_delay_ms"`
// EndpointSensitivity tunes how readily Soniox calls a turn ended.
EndpointSensitivity settings.Opt[float64] `settings:"endpoint_sensitivity"`
// EndpointLatencyAdjustmentLevel trades endpoint latency against accuracy.
EndpointLatencyAdjustmentLevel settings.Opt[int] `settings:"endpoint_latency_adjustment_level"`
// ClientReferenceID labels the session in Soniox's own records.
ClientReferenceID settings.Opt[string] `settings:"client_reference_id"`
// EnableReconnect reconnects a dropped connection to the same Soniox
// stream, keeping the transcript and the audio sent around the drop.
// Soniox bills the up to 20 s a dropped stream waits for the reconnect.
EnableReconnect settings.Opt[bool] `settings:"enable_reconnect"`
// EnableAgentTextInput sends each completed bot reply to Soniox as agent
// text, on models that support it (stt-rt-v6 and later).
EnableAgentTextInput settings.Opt[bool] `settings:"enable_agent_text_input"`
// EnableEchoCancellation sends the bot's speech as agent text while it
// plays, which lets Soniox cancel the bot's echo. It implies
// EnableAgentTextInput.
EnableEchoCancellation settings.Opt[bool] `settings:"enable_echo_cancellation"`
// AgentTextLeadMs is how far ahead of playback each of the bot's words is
// sent, in milliseconds.
AgentTextLeadMs settings.Opt[int] `settings:"agent_text_lead_ms"`
// SpeakerFormat formats each diarized speaker run: {speaker} is the
// speaker label, {text} the transcript text, and {speaker_number} the
// speaker's order of first appearance in the session (1, 2, ...). No value
// leaves the text as it is. Applied locally, so changing it does not
// reopen the session.
SpeakerFormat settings.Opt[string] `settings:"speaker_format"`
}
Settings is the part of the Soniox configuration that can change while the pipeline runs. Soniox is told all of it in the handshake that opens a session, so a change to any of it reopens the session.
func (*Settings) ApplyUpdate ¶ added in v0.7.0
ApplyUpdate merges an update, implementing settings.Updater. Soniox reads the language hints when a session opens, not the language, so a language the update gives is moved into the hints rather than stored. Hints given in the same update win, and a language outside the catalog stays where it was given.
type TTSConfig ¶ added in v0.1.0
type TTSConfig struct {
// APIKey is the Soniox API key, sent on the WebSocket handshake. Required.
APIKey string `validate:"required"`
// URL overrides the synthesis WebSocket endpoint; empty uses the hosted
// endpoint.
URL string
// Model is the synthesis model; empty uses a current default.
Model string
// Voice is a stock voice name (for example "Adrian") or the UUID of a cloned
// voice belonging to the API key's project; empty uses a default.
Voice string
// Language for synthesis; the zero value uses English. Mapped to Soniox's
// language code, which is the base code: a regional language is sent as
// its base.
Language language.Language
// SampleRate is the PCM rate requested from Soniox and emitted downstream;
// 0 uses 24 kHz. Soniox accepts 8000, 16000, 24000, 44100 and 48000.
SampleRate int `validate:"omitempty,oneof=8000 16000 24000 44100 48000"`
// AudioFormat is the audio format Soniox sends; empty uses "pcm_s16le",
// the raw 16-bit PCM the pipeline carries. The audio is passed on as it
// arrives, so any other format needs decoding downstream.
AudioFormat string
// Speed multiplies the speaking rate from 0.7 to 1.3; nil leaves it unset
// and uses Soniox's default of 1.0.
Speed *float64 `validate:"omitempty,min=0.7,max=1.3"`
// ReduceSilence shortens the pauses between words so the speech flows more
// tightly, without changing how fast the words themselves are spoken. Only
// the models that support silence reduction accept it. Nil leaves it unset
// and uses Soniox's default, off.
ReduceSilence *bool
// ClientReferenceID labels the request in Soniox's own usage records, so the
// audio generated can be attributed to a customer or a session. Empty omits
// it, and Soniox ignores it for a temporary API key.
ClientReferenceID string
// TextAggregation is how streamed text is grouped before synthesis:
// frames.TextTypeSentence (the zero value) sends the turn's text to its
// stream a sentence at a time, frames.TextTypeToken streams it as it is
// generated.
TextAggregation frames.TextType
// WordTimestamps requests per-character timings and drives the word-aligned
// text path: the TTS base emits a TTSTextFrame for each spoken word as its
// audio plays, mapped back to its original written form, so the assistant
// context records only what was actually spoken before an interruption. It
// is on by default; set it to false to fall back to aggregated text frames.
WordTimestamps *bool
// Websocket configures the connection: whether and how it reconnects, and
// how long it waits on a peer that has stopped answering.
Websocket wsservice.Options
}
TTSConfig configures the Soniox streaming TTS service.
type TTSService ¶ added in v1.0.0
TTSService is the Soniox text-to-speech service NewTTS builds.
func NewTTS ¶ added in v0.1.0
func NewTTS(cfg TTSConfig) *TTSService
NewTTS builds a Soniox streaming TTS service.
It holds one connection open for the call, opened when the pipeline starts, and speaks each turn on a stream of its own on it, named by the turn's audio context: the stream is opened as the turn starts, each sentence is sent to it as it is ready, and it is closed once the turn's text is complete. Soniox tags its audio with the stream, so the audio still arriving for a turn the user cut off is dropped rather than spoken over the next one, and the stream is canceled. When the connection drops it is restored with backoff, and when that keeps failing the service reports a permanent error and becomes unusable.
type TTSSettings ¶ added in v0.6.0
type TTSSettings struct {
settings.TTS
// Speed multiplies the speaking rate, from 0.7 to 1.3.
Speed settings.Opt[float64] `settings:"speed"`
// ReduceSilence shortens the pauses between words.
ReduceSilence settings.Opt[bool] `settings:"reduce_silence"`
// ClientReferenceID labels each request in Soniox's usage logs.
ClientReferenceID settings.Opt[string] `settings:"client_reference_id"`
}
TTSSettings is the part of the synthesis configuration that can change while the pipeline runs.
Voice is a stock voice name (for example "Adrian") or the UUID of a cloned voice in the project owning the API key. Speed multiplies the speaking rate from 0.7 to 1.3, ReduceSilence shortens the pauses between words without changing how fast the words themselves are spoken (only the models that support silence reduction accept it), and ClientReferenceID labels each request in Soniox's usage logs, for attributing usage to a customer or a session (ignored for a temporary API key). Those left without a value are left to Soniox.
They all travel in the configuration that opens a stream, so a change needs no new connection: the turn's stream is flushed, and the rest of the turn opens a fresh one with the new values.