Documentation
¶
Index ¶
- Constants
- func DefaultConfigPath() string
- func LoadConfig(path string) (configFile, error)
- func NewEmbeddedHandler(log *slog.Logger, bridge MediaBridgeProvider, textSessions TextSessionServer) http.Handler
- func NewHandler(log *slog.Logger, issuers []TrustedIssuerConfig, bridge MediaBridge, ...) (http.Handler, error)
- func NewWebRTCConfig() configdata.WebRTC
- func TranscriptionSampleRate(score scoreboard.Score, model string) int
- func ValidOpusRate(rate int) bool
- type ASRConfig
- type ASREngine
- type Choice
- type ChoiceMediaBridge
- type ChoiceName
- type ChoiceTextSessionServer
- type CloseSessionResp
- type Config
- type DebugConfig
- type DiagnosticMediaBridge
- type HealthResp
- type LLMConfig
- type MediaBridge
- type MediaBridgeProvider
- type ModelConfig
- type OfferResp
- type PipelineConfig
- type RealtimeConfig
- type ResolvedConfig
- type RuntimeConfig
- type ServerConfig
- type TTSConfig
- type TTSEngine
- type TextSessionServer
- type TrustedIssuerConfig
- type VoiceChoiceProvider
- type VoiceConfig
- type VoiceRTCErrorProvider
Constants ¶
const ConfigFileName = "voice-choices.toml"
ConfigFileName is the name of the voice declarations file in a gateway or host configuration directory.
const DefaultSlots = 2
DefaultSlots is the number of concurrent requests of a managed llama.cpp server whose slots are omitted.
const DefaultVoiceScope = "voice.session"
DefaultVoiceScope is the OAuth scope a gateway requires on an OAuth access token that authorizes a voice session.
Variables ¶
This section is empty.
Functions ¶
func DefaultConfigPath ¶
func DefaultConfigPath() string
DefaultConfigPath returns the canonical standalone voice gateway config path.
func LoadConfig ¶
LoadConfig reads standalone gateway settings with listener defaults, and the voice declarations from ReadConfig in the same directory; call Resolve before startup. Relative geo_db paths resolve beside this file; leading ~ expands to home. Hosts call ReadConfig and Config.Resolve instead.
func NewEmbeddedHandler ¶
func NewEmbeddedHandler(log *slog.Logger, bridge MediaBridgeProvider, textSessions TextSessionServer) http.Handler
NewEmbeddedHandler returns voice gateway routes for a caller that already enforces request authentication before dispatch. textSessions may be nil. log receives request failures.
Hosts may exempt only the browser text ticket redemption GET from their authentication middleware: that handler authenticates its single-use ticket. Ticket issuance and native text WebSocket handshakes require host authentication.
func NewHandler ¶
func NewHandler( log *slog.Logger, issuers []TrustedIssuerConfig, bridge MediaBridge, textSessions TextSessionServer, ) (http.Handler, error)
NewHandler validates standalone issuer policy and returns authenticated voice gateway routes. textSessions may be nil when no backend serves text sessions. log receives request failures.
func NewWebRTCConfig ¶
func NewWebRTCConfig() configdata.WebRTC
NewWebRTCConfig returns the defaults: an ephemeral port and Google's public STUN server.
func TranscriptionSampleRate ¶
func TranscriptionSampleRate(score scoreboard.Score, model string) int
TranscriptionSampleRate returns the input rate of the live transcription session that score qualifies for model at a ValidOpusRate, or 0 when score qualifies none. A row listing model wins; otherwise the provider's first qualifying row stands for every model, since a llama.cpp model is an arbitrary GGUF and providers fix the transcription rate in their client.
func ValidOpusRate ¶
ValidOpusRate reports whether Opus decodes natively to rate, so the gateway can feed a stage at rate without resampling.
Types ¶
type ASRConfig ¶
type ASRConfig struct {
ID string
Label string
Engine ASREngine
Provider string
Remote string
Model string
// ContextSize is the managed llama.cpp context per slot in tokens, 512 to
// 262144, and is required for a managed server. Each session carries one
// utterance of at most a minute.
ContextSize int
// Slots is the number of concurrent utterances of a managed llama.cpp
// server, 1 to 16; zero selects DefaultSlots. A transcription session
// holds its slot until the utterance's final transcript, so further
// utterances wait for a slot while their audio queues. The server holds
// Slots × ContextSize tokens of KV cache.
Slots int
}
ASRConfig configures a speech-to-text adapter.
Provider is used only by the genai engine, and Remote only by the genai, nemospeech and vosk engines.
type ASREngine ¶
type ASREngine string
ASREngine selects how utterances are transcribed.
const ( // ASREngineGenAI uses a genai provider's live transcription session, one // per utterance, fed at the rate TranscriptionSampleRate selects. // Provider's genai scoreboard must qualify a transcription session at a // ValidOpusRate, and Model is required. With llamacpp and no Remote, the // gateway starts a dedicated managed server; other providers use their // configured endpoint. ASREngineGenAI ASREngine = "genai" // ASREngineWhistle runs the managed Cactus Whistle recognizer. // Model optionally names local .cact weights; empty downloads the dedicated // Whistle model. Provider and Remote must be empty. ASREngineWhistle ASREngine = "whistle" // ASREngineNemoSpeech runs NVIDIA NeMo-Speech.cpp. Model is required and // is one of nemospeech.Models. Without Remote, the gateway installs the // pinned release and starts a dedicated server, which downloads the model // into NeMo-Speech.cpp's own cache; Remote selects an operator-owned server // that loaded Model. Provider must be empty. ASREngineNemoSpeech ASREngine = "nemospeech" // ASREngineVosk runs a Vosk recognizer. Model is required and is one of // vosk.Models. Without Remote, the gateway downloads the model into the // genaipy cache and starts a dedicated worker; Remote selects an // operator-owned vosk-server that loaded Model. Provider must be empty. ASREngineVosk ASREngine = "vosk" )
type Choice ¶
type Choice interface {
// contains filtered or unexported methods
}
Choice is a typed pipeline configuration: *RealtimeConfig, *LLMConfig, or *PipelineConfig. Resolve selects their defaults; each validates itself.
type ChoiceMediaBridge ¶
type ChoiceMediaBridge interface {
VoiceChoiceProvider
HandleChoiceOffer(ctx context.Context, sdp, choiceID string) (sdpAnswer, sessionID string, err error)
}
ChoiceMediaBridge advertises and selects named voice backends. The MediaBridge methods continue to operate on the default choice.
type ChoiceName ¶
type ChoiceName struct {
// ID is the configured id clients save and select.
ID string
Label string
}
ChoiceName is the advertised identity of one choice.
type ChoiceTextSessionServer ¶
type ChoiceTextSessionServer interface {
VoiceChoiceProvider
ServeTextChoice(ctx context.Context, w http.ResponseWriter, r *http.Request, choiceID string) error
}
ChoiceTextSessionServer selects a named backend for a text session.
type CloseSessionResp ¶
type CloseSessionResp struct {
Status string `json:"status"`
}
CloseSessionResp is returned after closing a voice gateway session.
type Config ¶
type Config struct {
Runtime RuntimeConfig
Realtime []RealtimeConfig
// ASR, LLM, and TTS entries are offered in declaration order.
ASR []ASRConfig
LLM []LLMConfig
TTS []TTSConfig
Voice []VoiceConfig
}
Config declares reusable voice stages and presets. ReadConfig loads it from ConfigFileName or the defaults embedded in this module. Stage entries retain declaration order. Resolve validates references and produces runtime configuration without changing declarations.
Every entry has an id that clients save and send back, so it must stay the same while the entry's other settings change. An id is 1 to 64 lowercase ASCII letters, digits, '-' or '_', starting with a letter or digit. Ids are unique within each advertised namespace: voice choices ([[realtime]], [[llm]], and [[voice]] together), recognition models ([[asr]]), and synthesis models ([[tts]]). Namespaces are independent, so an [[asr]] and an [[llm]] entry may share an id; [[voice]] references each stage in its own namespace.
An embedding host calls ReadConfig with its configuration directory and Resolve during configuration validation, and passes the result through startup. It restarts or reloads when ConfigFileName appears, changes, or disappears. Before creating the bridge it calls Available, checks caller cancellation, and validates the filtered result; an empty catalog prevents startup. It passes the resolved configuration and a validated configdata.WebRTC to voicertc.NewBridge. The host owns its listener, deployment mode, authentication, session admission, and the private directory and lifetime of transcript activity logs.
func ReadConfig ¶
ReadConfig reads dir/ConfigFileName, or the declarations embedded in this module when that file does not exist. A present file replaces the defaults entirely. Unknown keys are errors that name the file and position.
func (*Config) Resolve ¶
func (c *Config) Resolve() (ResolvedConfig, error)
Resolve validates declarations, selects omitted defaults, and expands preset references into effective runtime settings. A [[voice]] entry resolves each stage id in its own table; an entry without an id resolves no reference. Reference errors join ResolvedConfig.Validate errors, so a missing id is reported beside the reference that fails because of it. It owns its result slices and leaves declarations unchanged. Recognition, language, and synthesis choices retain declaration order in standalone and embedded host configurations.
type DebugConfig ¶
type DebugConfig struct {
// Trace is the output file for a Go execution trace; empty disables tracing.
Trace string
}
DebugConfig configures standalone execution tracing.
type DiagnosticMediaBridge ¶
type DiagnosticMediaBridge interface {
DiagnoseVoiceRTC(ctx context.Context, sessionID string, client *voicev2.VoiceRTCClientDiagnostics) voicev2.VoiceRTCDiagnosticsResp
}
DiagnosticMediaBridge returns structured WebRTC connectivity diagnostics.
type HealthResp ¶
type HealthResp struct {
Status string `json:"status"`
}
HealthResp is returned by GET /api/voicegateway/v2/voice/health.
type LLMConfig ¶
type LLMConfig struct {
ID string
Label string
ModelConfig
// ContextSize is the managed llama.cpp context per slot in tokens, 512 to
// 262144, and is required for a managed server. Conversation history is
// kept whole, so requests that outgrow it fail.
ContextSize int
// Slots is the number of concurrent requests of a managed llama.cpp
// server, 1 to 16; zero selects DefaultSlots. Further requests queue. The
// server holds Slots × ContextSize tokens of KV cache.
Slots int
}
LLMConfig selects an LLM with independently chosen speech stages.
Clients may provide speech or select independently configured gateway stages. Only selected gateway stages initialize their models and workers.
type MediaBridge ¶
type MediaBridge interface {
HandleOffer(ctx context.Context, sdp string) (sdpAnswer, sessionID string, err error)
Close(sessionID string)
}
MediaBridge is the WebRTC media transport used by the voice gateway API.
type MediaBridgeProvider ¶
type MediaBridgeProvider func() MediaBridge
MediaBridgeProvider returns the current WebRTC media transport.
type ModelConfig ¶
type ModelConfig struct {
// LlamaCPPServer starts a managed llama.cpp server instead of connecting to Remote.
LlamaCPPServer bool
Provider string
// Auth selects the existing Codex subscription when set to "codex" on
// openai or openairesponses. Empty preserves API-key authentication.
Auth openairesponses.Auth
// Remote is a server origin, except for openaicompatible, which requires the
// complete chat completions endpoint URL, including its path.
Remote string
Model string
// Effort selects off, low, medium, high, xhigh, or max. Empty
// omits the effort option, preserving provider defaults. Supported levels
// depend on the provider and model; off requests the lowest supported effort.
Effort genai.EffortLevel
// OpenRouterSort prioritizes OpenRouter providers by latency, price, or
// throughput. Empty preserves OpenRouter's default routing.
OpenRouterSort openrouter.ProviderSort
// APIKeyName names the environment variable containing the bearer token
// for an openaicompatible endpoint. The credential is never stored in TOML.
// A named variable must be nonempty in the gateway process environment.
// Authenticated requests, including redirects, are confined to Remote.
APIKeyName string
}
ModelConfig selects a provider, model, and managed or remote endpoint.
Model is required. Providers use their native API-key environment variables unless Auth selects the Codex subscription or APIKeyName selects a token for an openaicompatible endpoint.
func (*ModelConfig) NewProvider ¶
func (c *ModelConfig) NewProvider(ctx context.Context, opts ...genai.ProviderOption) (genai.Provider, error)
NewProvider constructs the configured client and identifies subscription requests as gomode. Model may be omitted for discovery. Managed llama.cpp runtimes must resolve their endpoint before constructing their client. Effort and provider routing preferences apply to individual generation calls. A client returned with a constructor error is closed before returning.
type PipelineConfig ¶
type PipelineConfig struct {
// ID is the [[voice]] id; it is empty for combinations composed per session.
ID string
Label string
// TextOnly disables gateway speech processing. Clients transcribe and speak;
// the choice serves text sessions only and never initializes ASR or TTS.
// ASR and TTS settings must be omitted when TextOnly is true.
TextOnly bool
ASR ASRConfig
// LLM must support function tools. Its endpoint receives transcripts, the
// system instruction, and service-item context, even when speech stays local.
LLM LLMConfig
TTS TTSConfig
// UnavailableASR and UnavailableTTS retain choice identity while filtering
// speech capabilities after provider availability checks.
}
PipelineConfig composes recognition, language generation, and synthesis adapters.
ASR and TTS are independently optional. A configured stage defaults to gateway ownership; an omitted stage requires client speech. Each configured stage needs explicit engine/model selection, except for the ASR engines documented below.
type RealtimeConfig ¶
type RealtimeConfig struct {
ID string
Label string
ModelConfig
// Staged uses llama.cpp chat generation with audio input and thinking,
// followed by speech synthesis on the same model instead of realtime output.
// Resolve selects effort "medium" when omitted.
Staged bool
CacheDir string
Threads int
// Slots is 1 to 16; Resolve selects DefaultSlots when omitted.
Slots int
// ContextSize is tokens per slot, 512 to 131072, and is required for a
// managed server. A realtime conversation that outgrows it ends.
ContextSize int
MaxOutputTokens int64
}
RealtimeConfig configures a native audio pipeline. For llama.cpp, endpoint capacity is an operator-declared reservation limit, not discovery.
func (*RealtimeConfig) CacheDirectory ¶
func (c *RealtimeConfig) CacheDirectory() (string, error)
CacheDirectory returns the configured managed runtime cache or its platform default.
type ResolvedConfig ¶
type ResolvedConfig struct {
Runtime RuntimeConfig
Realtime []RealtimeConfig
LLM []LLMConfig
Pipelines []PipelineConfig
Recognition []ASRConfig
Synthesis []TTSConfig
}
ResolvedConfig holds effective runtime settings produced by Config.Resolve. Choices are offered in realtime, LLM, then pipeline order. Listeners and authentication policy are owned by the caller.
func (*ResolvedConfig) Available ¶
func (c *ResolvedConfig) Available(ctx context.Context, log *slog.Logger) ResolvedConfig
Available returns a copy containing only choices whose providers are available. Call Validate first. Each configured provider using a default endpoint is probed once, and probe clients are closed before returning. Missing providers and custom credentials produce warnings. Unavailable speech stages remove their gateway-owned combinations while keeping client-owned speech selectable under the same choice ID. Managed runtimes and explicit local endpoints remain selectable without probing their default servers. Probes share a one-minute deadline, shortened by earlier caller cancellation. Validate the result if no choices would prevent startup. Availability does not guarantee access to a model. log receives the warnings.
func (*ResolvedConfig) Choices ¶
func (c *ResolvedConfig) Choices() iter.Seq2[ChoiceName, Choice]
Choices iterates names and pipeline configurations in client preference order, preserving entry order within each section. The configurations belong to c.
func (*ResolvedConfig) Validate ¶
func (c *ResolvedConfig) Validate() error
Validate returns an error if c is not a usable runtime configuration.
type RuntimeConfig ¶
type RuntimeConfig struct {
// IdleTimeoutSeconds starts when the last session closes. Resolve selects
// 3600 when omitted.
IdleTimeoutSeconds int
// MaxInstances counts complete choices, including ASR/LLM/TTS. Resolve
// selects 2 when omitted.
MaxInstances int
}
RuntimeConfig bounds loaded pipelines, LLMs, and native llama.cpp audio choices, including all their providers and managed workers. Active sessions pin their choice; capacity waits never evict active sessions. Remote servers remain host-owned.
type ServerConfig ¶
type ServerConfig struct {
geoip.Config
configdata.WebRTC
HTTP string
// ExternalURL is the expected public HTTP(S) origin. Empty accepts the request authority.
ExternalURL string
// TrustedProxies lists direct proxy CIDRs allowed to supply client IP headers.
TrustedProxies []string
// DebugFrontend enables the unauthenticated live-test UI on the API listener.
DebugFrontend bool
LogLevel slog.Level
}
ServerConfig configures gateway listeners, HTTP policies and standalone logging.
func (*ServerConfig) Validate ¶
func (c *ServerConfig) Validate() error
Validate checks HTTP policies and the WebRTC listener.
type TTSConfig ¶
type TTSConfig struct {
ID string
Label string
Engine TTSEngine
Provider string
Remote string
Model string
Voice string
// ContextSize is the managed llama.cpp context per slot in tokens, 512 to
// 262144, and is required for a managed server. Each request carries one
// reply.
ContextSize int
// Slots is the number of concurrent requests of a managed llama.cpp
// server, 1 to 16; zero selects DefaultSlots. Further requests queue. The
// server holds Slots × ContextSize tokens of KV cache.
Slots int
}
TTSConfig selects a speech synthesis engine.
Engine and Model are required. Voice may be omitted for provider synthesis; fixed-voice models and model defaults then select the speaker. Provider and Remote are used only by the genai engine.
type TTSEngine ¶
type TTSEngine string
TTSEngine selects how assistant text is synthesized.
const ( // TTSEngineGenAI uses a registered provider's dedicated speech endpoint. // llama.cpp starts a managed server when Remote is omitted. TTSEngineGenAI TTSEngine = "genai" // TTSEngineKittenTTS runs the managed KittenTTS worker. // Remote must be empty; the shared genaipy runtime owns Python and caches. // Model must be one whose voices genaipy lists; each voice speaks one // language, and Voice is the voice of sessions in its language. TTSEngineKittenTTS TTSEngine = "kittentts" )
type TextSessionServer ¶
type TextSessionServer interface {
// ServeTextSession runs one text session on the HTTP response. It owns the
// response and writes its own error response, so the caller only logs a
// returned error.
ServeTextSession(ctx context.Context, w http.ResponseWriter, r *http.Request) error
}
TextSessionServer serves bidirectional text voice sessions where the client performs speech recognition and synthesis.
type TrustedIssuerConfig ¶
type TrustedIssuerConfig struct {
// Service is the service kind allowed to issue tokens, for example "example".
Service string
// Issuer is the backend origin that owns the signing key.
//
// It must match the service authorization base URL and the token backend origin.
Issuer string
// PublicKey is the imported Ed25519 public key used to verify scoped tokens from issuer.
//
// The expected format is the value returned by gomode.EncodeServiceSigningPublicKey.
PublicKey string
// OAuth enables OAuth 2.0 access token verification through discovery and JWKS.
OAuth bool
// Scope is the OAuth scope a token must carry. It defaults to
// DefaultVoiceScope when empty.
Scope string
}
TrustedIssuerConfig configures a service backend trusted to issue tokens.
Exactly one of PublicKey or OAuth selects the token form. PublicKey verifies the transitional scoped Ed25519 token. OAuth verifies a standard OAuth 2.0 access token through issuer metadata discovery and its published JWKS.
func (*TrustedIssuerConfig) OAuthScope ¶
func (c *TrustedIssuerConfig) OAuthScope() string
OAuthScope returns the scope an OAuth token from this issuer must carry.
type VoiceChoiceProvider ¶
type VoiceChoiceProvider interface {
VoiceChoices() voicev2.VoiceChoicesResp
}
VoiceChoiceProvider advertises the choices available through a transport.
type VoiceConfig ¶
VoiceConfig names the stages composed into one preset by their ids. ASR and TTS are optional; an omitted stage requires client-owned speech.
type VoiceRTCErrorProvider ¶
VoiceRTCErrorProvider supplies the retained gateway error for v1 diagnostics.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package api provides shared voice gateway API infrastructure.
|
Package api provides shared voice gateway API infrastructure. |
|
v1
Package v1 is the voice gateway contract published with Go Mode v0.3.0.
|
Package v1 is the voice gateway contract published with Go Mode v0.3.0. |
|
data
|
|
|
v1
Package v1 defines version 1 of the voice gateway config.toml and voice-choices.toml schemas.
|
Package v1 defines version 1 of the voice gateway config.toml and voice-choices.toml schemas. |
|
Package policy owns voice instructions shared by gateways and bundled offline engines.
|
Package policy owns voice instructions shared by gateways and bundled offline engines. |
|
Package voicertc implements WebRTC voice sessions through the voice gateway protocol.
|
Package voicertc implements WebRTC voice sessions through the voice gateway protocol. |
|
data/v1
Package v1 defines version 1 of the persisted voice activity records, independent of the session protocol.
|
Package v1 defines version 1 of the persisted voice activity records, independent of the session protocol. |