Documentation
¶
Overview ¶
Package live exposes the low-level Voice Agent realtime-protocol types.
This is the public-API surface for building custom realtime providers (Gemini Live, OpenAI Realtime, or a third-party WebSocket model) and for libraries that drive a SpeechKit session directly without going through the higher-level [Service] in the parent package.
Most embedders use the parent [voiceagent] package or github.com/kombifyio/SpeechKit/pkg/speechkit/agentkit instead; reach for this package only when you need to plug in your own provider or read the raw LiveMessage stream.
Stability: Stable — no breaking change without a minor version bump and a changelog callout.
Index ¶
- Constants
- Variables
- func AppendContextPrompt(base, contextPrompt string) string
- func EventTypesContain(values []LiveEventType, want LiveEventType) bool
- func FrameUntrustedToolOutput(source, lead, output string) string
- func NormalizeProviderID(providerOrProfile string) string
- func RenderHostInstructionUpdate(cfg LiveConfig) string
- func ShouldTryFallback(primary, fallback string) bool
- func UpsampleMicPCM16Mono(src []byte) []byte
- type ActivityDetectionPolicy
- type ActivityHandling
- type Callbacks
- type CapabilityRequirement
- type ContextCompressionPolicy
- type ContinuousDuplexProvider
- type EndSensitivity
- type HostPromptEvent
- type HostPromptEventType
- type HostPromptKind
- type IdleConfig
- type IdleTimer
- type LatencyProfile
- type LiveCapabilityFlag
- type LiveConfig
- type LiveEndpointReporter
- type LiveEventType
- type LiveInstructionUpdater
- type LiveMessage
- type LiveModelDescriptor
- type LivePolicies
- type LiveProvider
- type LiveReconnector
- type LiveSessionCapabilities
- type ModelLifecyclePolicy
- type ProviderDescriptor
- type ProviderFallback
- type ProviderFallbackKind
- type ProviderIntent
- type ProviderIntentError
- type ProviderRejection
- type ProviderSelectionPolicy
- type ResolvedLiveOptions
- type ResolvedProviderPlan
- type ResumeHandle
- type Session
- func (s *Session) AdvanceWorkflowStep(ctx context.Context, reason string) error
- func (s *Session) CurrentState() State
- func (s *Session) EndAudioStream() error
- func (s *Session) ProviderName() string
- func (s *Session) SendAgentProgress(text string) (bool, error)
- func (s *Session) SendAudio(chunk []byte) error
- func (s *Session) SendText(text string) error
- func (s *Session) SendToolResponse(response ToolResponse) error
- func (s *Session) SendUntrustedToolOutput(source, lead, output string) (bool, error)
- func (s *Session) SetLogger(l *slog.Logger)
- func (s *Session) Shutdown(ctx context.Context) error
- func (s *Session) Start(ctx context.Context, cfg LiveConfig, idleCfg IdleConfig) error
- func (s *Session) Stop()
- func (s *Session) StopWithTimeout(timeout time.Duration)
- type SessionCapabilities
- type StartSensitivity
- type State
- type ThinkingLevel
- type ThinkingPolicy
- type ToolBehavior
- type ToolCall
- type ToolDefinition
- type ToolResponse
- type ToolResponseScheduling
- type TranscriptionMode
- type TurnCoverage
- type WorkflowConfig
- type WorkflowStep
Examples ¶
Constants ¶
const ( // DefaultSpeakingSettleDelay is the existing output-cadence grace for // continuous-duplex providers whose protocol has no turn-done event. DefaultSpeakingSettleDelay = 900 * time.Millisecond // DefaultStopCloseTimeout bounds how long Stop waits for provider.Close. // Deepgram/AssemblyAI Close has no timeout of its own; holding the // session mutex across an unbounded close wedged every caller, including // the server target and SDK hosts that do not wrap Stop themselves. DefaultStopCloseTimeout = 3 * time.Second )
Variables ¶
var ( // ErrNotConnected is returned by session operations before Connect // succeeded or after Close. ErrNotConnected = errors.New("speechkit live: not connected") // ErrSessionNotReady is returned when the transport is up but the // provider has not yet acknowledged the session. ErrSessionNotReady = errors.New("speechkit live: session is not ready") // ErrMissingAPIKey is returned by Connect when the provider requires an // API key and none was configured. ErrMissingAPIKey = errors.New("speechkit live: APIKey is required") // ErrMissingEndpoint is returned by Connect when the provider requires an // explicit endpoint and none was configured. ErrMissingEndpoint = errors.New("speechkit live: Endpoint is required") // ErrNoResumableSession is returned by Resume when the provider has no // session id to resume. ErrNoResumableSession = errors.New("speechkit live: no resumable session id") )
Sentinel errors shared by every LiveProvider implementation. Providers wrap them with their own prefix, so hosts test with errors.Is instead of matching provider-specific strings.
var ErrNoMatchingProvider = errors.New("speechkit live: no provider satisfies intent")
ErrNoMatchingProvider is the sentinel every ProviderIntentError unwraps to; test for it with errors.Is.
Functions ¶
func AppendContextPrompt ¶ added in v0.64.3
AppendContextPrompt appends contextPrompt to base under a "Context:" heading. Both are trimmed; when either is empty the other is returned.
func EventTypesContain ¶ added in v0.64.3
func EventTypesContain(values []LiveEventType, want LiveEventType) bool
EventTypesContain reports whether want appears in values. Frames carry several normalized meanings when one provider event maps to more than one, so callers ask rather than compare a single field.
func FrameUntrustedToolOutput ¶ added in v0.74.0
FrameUntrustedToolOutput renders the in-band framing used by Session.SendUntrustedToolOutput. Realtime providers accept only plain text turns, so the separation is textual: a random per-message marker that the payload cannot predict, the payload stripped of control characters and of anything resembling a marker, and a bounded length.
func NormalizeProviderID ¶ added in v0.47.0
NormalizeProviderID maps common provider aliases and public profile ids to the canonical provider id used by ProviderDescriptor.Provider.
func RenderHostInstructionUpdate ¶
func RenderHostInstructionUpdate(cfg LiveConfig) string
RenderHostInstructionUpdate turns a workflow step change into a provider text update. Providers that implement LiveInstructionUpdater receive the structured LiveConfig instead.
func ShouldTryFallback ¶ added in v0.64.3
ShouldTryFallback reports whether a configured fallback model is worth attempting after the primary failed: it must be set, and it must not be the model that just failed.
func UpsampleMicPCM16Mono ¶ added in v0.64.3
UpsampleMicPCM16Mono linearly interpolates a 16-bit signed little-endian PCM mono buffer from SpeechKit's mic rate (16 kHz) to OpenAI's input rate (24 kHz). For the 16 kHz to 24 kHz path (ratio 2:3) the cost is negligible compared to the WS round-trip; CPU profiling at scale should still consider replacing this with a polyphase FIR resampler if it shows up as a hot path.
Types ¶
type ActivityDetectionPolicy ¶
type ActivityDetectionPolicy struct {
Automatic bool
StartSensitivity StartSensitivity
EndSensitivity EndSensitivity
PrefixPaddingMs int32
SilenceDurationMs int32
ActivityHandling ActivityHandling
TurnCoverage TurnCoverage
}
ActivityDetectionPolicy defines server-side VAD/session turn behavior.
type ActivityHandling ¶
type ActivityHandling string
ActivityHandling controls what the provider should do when new activity starts.
const ( // ActivityHandlingUnspecified keeps the provider default. ActivityHandlingUnspecified ActivityHandling = "" // ActivityHandlingNoInterrupt lets model playback finish even when the // user starts speaking (barge-in disabled). ActivityHandlingNoInterrupt ActivityHandling = "no_interrupt" // ActivityHandlingStartOfActivityInterrupts stops model playback as soon // as user activity starts (barge-in). ActivityHandlingStartOfActivityInterrupts ActivityHandling = "start_of_activity_interrupts" )
Activity handling values for ActivityDetectionPolicy.
type Callbacks ¶
type Callbacks struct {
OnStateChange func(state State)
OnAudio func(audio []byte) // Audio chunk to play
OnText func(text string) // Text for display (speech bubble)
OnError func(err error) // Terminal session failure, followed by cleanup.
// OnTurnError reports a recoverable turn failure. The session returns to
// listening and remains available for the next turn; OnError is not called.
OnTurnError func(err error)
OnInputTranscript func(text string, done bool) // User speech transcribed
OnOutputTranscript func(text string, done bool) // Model speech transcribed
OnToolCall func(call ToolCall)
OnToolCallCancellation func(ids []string)
// OnHostPrompt may reject a Started event by returning false. Sent and
// SendFailed are correlated terminal phases for an accepted prompt; their
// return values are ignored.
OnHostPrompt func(event HostPromptEvent) bool
OnInterrupted func() // User interrupted model (barge-in)
OnSessionEnd func() // Session ended (error, GoAway failure, or deactivation)
}
Callbacks are event handlers for UI integration with a low-level Session.
This is the rich Callbacks struct used by the low-level Session runtime. The higher-level [voiceagent.Callbacks] in the parent package carries only the three most-common handlers (OnAudio, OnText, OnError) and is the right shape for the embedded [voiceagent.Service]; reach for this struct only when wiring a custom realtime host.
type CapabilityRequirement ¶ added in v0.47.0
type CapabilityRequirement struct {
Capability LiveCapabilityFlag `json:"capability"`
Required bool `json:"required,omitempty"`
}
CapabilityRequirement is one capability of a ProviderIntent: Required makes it mandatory, otherwise it is only preferred.
type ContextCompressionPolicy ¶
ContextCompressionPolicy defines how the live API should compress long sessions.
type ContinuousDuplexProvider ¶ added in v0.74.0
type ContinuousDuplexProvider interface {
ContinuousDuplex() bool
}
ContinuousDuplexProvider is implemented by a LiveProvider whose protocol has no turn boundaries at all: a full-duplex voice layer streams audio and transcript fragments without a turn-done event. The session then settles each turn on its speaking timer as the normal path rather than as a provider fault.
type EndSensitivity ¶
type EndSensitivity string
EndSensitivity controls how aggressively automatic activity detection commits speech end.
const ( EndSensitivityLow EndSensitivity = "low" EndSensitivityMedium EndSensitivity = "medium" EndSensitivityHigh EndSensitivity = "high" )
End sensitivities for ActivityDetectionPolicy: high commits a speech end soonest after the user pauses, low waits longest.
type HostPromptEvent ¶ added in v0.50.0
type HostPromptEvent struct {
ID uint64
Kind HostPromptKind
Type HostPromptEventType
}
HostPromptEvent correlates the synchronous authorization opening with a possible provider send failure. IDs are session-local and never reused.
type HostPromptEventType ¶ added in v0.50.0
type HostPromptEventType string
HostPromptEventType is the phase of a host prompt reported in a HostPromptEvent.
const ( HostPromptStarted HostPromptEventType = "started" HostPromptSent HostPromptEventType = "sent" HostPromptSendFailed HostPromptEventType = "send_failed" )
Host prompt phases. Started is delivered synchronously before the prompt is sent and may be rejected through Callbacks.OnHostPrompt; exactly one of Sent or SendFailed follows for an accepted prompt.
type HostPromptKind ¶ added in v0.50.0
type HostPromptKind string
HostPromptKind identifies a trusted, locally generated text turn. These prompts are distinct from user audio and let hosts open an explicit playback generation instead of treating arbitrary out-of-turn model audio as an idle response.
const ( // HostPromptIdleReminder asks the model to check in with a user who has // been silent for [IdleConfig.ReminderAfter]. HostPromptIdleReminder HostPromptKind = "idle_reminder" // HostPromptIdleDeactivate asks the model to say goodbye before the // session is stopped after [IdleConfig.DeactivateAfter]. HostPromptIdleDeactivate HostPromptKind = "idle_deactivate" // HostPromptAgentProgress carries progress from a long-running host-side // tool (e.g. the external coding agent bridge) back into the dialogue. // Hosts deliver it only while the session is listening, so it never // collides with user speech or model playback. HostPromptAgentProgress HostPromptKind = "agent_progress" // HostPromptToolOutput carries output produced by an external tool (see // [Session.SendUntrustedToolOutput]). Its payload is untrusted data framed // by the host, not a trusted host instruction; it shares the listening- // only delivery rule of HostPromptAgentProgress. HostPromptToolOutput HostPromptKind = "tool_output" )
Host prompt kinds. The idle kinds are raised by IdleTimer.
type IdleConfig ¶
type IdleConfig struct {
ReminderAfter time.Duration // Default: 5 minutes
DeactivateAfter time.Duration // Default: 15 minutes
}
IdleConfig configures the idle timer behavior.
func DefaultIdleConfig ¶
func DefaultIdleConfig() IdleConfig
DefaultIdleConfig returns sensible defaults.
type IdleTimer ¶
type IdleTimer struct {
// contains filtered or unexported fields
}
IdleTimer manages reminder and auto-deactivation for Voice Agent.
func NewIdleTimer ¶
func NewIdleTimer(cfg IdleConfig, session *Session) *IdleTimer
NewIdleTimer creates an idle timer bound to a session.
type LatencyProfile ¶ added in v0.47.0
type LatencyProfile string
LatencyProfile expresses how a host trades response latency against accuracy. ResolveProviderIntent copies it onto the plan for hosts and providers to interpret; it does not influence provider selection.
const ( LatencyProfileInteractive LatencyProfile = "interactive" LatencyProfileBalanced LatencyProfile = "balanced" LatencyProfileAccuracy LatencyProfile = "accuracy" )
Latency profiles, from fastest response to highest accuracy.
type LiveCapabilityFlag ¶ added in v0.47.0
type LiveCapabilityFlag string
LiveCapabilityFlag names a realtime feature a ProviderDescriptor advertises. ProviderIntent requests flags and ResolveProviderIntent matches them against the descriptor catalog.
const ( // LiveCapabilityRealtimeAudio is native audio-to-audio dialogue. LiveCapabilityRealtimeAudio LiveCapabilityFlag = "realtime_audio" // LiveCapabilityToolCalling means the model can call host-side tools. LiveCapabilityToolCalling LiveCapabilityFlag = "tool_calling" // LiveCapabilityNativeWords means the host's Words vocabulary is applied // through provider-native boosting instead of prompt text. LiveCapabilityNativeWords LiveCapabilityFlag = "native_words" // LiveCapabilityTranscript means the session emits input and output // transcripts. LiveCapabilityTranscript LiveCapabilityFlag = "transcript" // LiveCapabilityInterruptions means the user can barge in on playback. LiveCapabilityInterruptions LiveCapabilityFlag = "interruptions" // LiveCapabilitySessionResume means the provider implements // [LiveReconnector] and can resume a session after a reconnect. LiveCapabilitySessionResume LiveCapabilityFlag = "session_resume" // LiveCapabilityNativeContextPrompt means a context prompt is passed as a // native session field. LiveCapabilityNativeContextPrompt LiveCapabilityFlag = "native_context_prompt" // LiveCapabilityNativeKeyterms means key terms boost recognition natively. LiveCapabilityNativeKeyterms LiveCapabilityFlag = "native_keyterms" // LiveCapabilityLanguageHints means recognition can be biased toward // given languages. LiveCapabilityLanguageHints LiveCapabilityFlag = "language_hints" // LiveCapabilitySpeakerStreaming means input transcripts can carry // speaker labels. LiveCapabilitySpeakerStreaming LiveCapabilityFlag = "speaker_streaming" // LiveCapabilityPrivacyRedaction means PII can be redacted from // transcripts. LiveCapabilityPrivacyRedaction LiveCapabilityFlag = "privacy_redaction" // LiveCapabilityVoiceFocus means background voices can be suppressed. LiveCapabilityVoiceFocus LiveCapabilityFlag = "voice_focus" // LiveCapabilityMedicalDomain means a medical vocabulary domain is // available. LiveCapabilityMedicalDomain LiveCapabilityFlag = "medical_domain" // LiveCapabilityReasoningEffort means the model's reasoning effort is // configurable. LiveCapabilityReasoningEffort LiveCapabilityFlag = "reasoning_effort" // LiveCapabilityTranslation means the session can translate speech. LiveCapabilityTranslation LiveCapabilityFlag = "translation" // LiveCapabilityTranscriptionOnly means the session can transcribe // without producing an agent reply. LiveCapabilityTranscriptionOnly LiveCapabilityFlag = "transcription_only" )
Capability flags. They mirror the framework's speechkit.Capability ids so hosts reason about realtime and cascaded profiles with one vocabulary.
type LiveConfig ¶
type LiveConfig struct {
Provider string // e.g. "deepgram", "assemblyai", "openai", "google"
ProfileID string // e.g. "realtime.openai.gpt-realtime-2"
Model string // provider-specific realtime model id
// StoredAgentID binds an AssemblyAI stored agent prepared by the host.
// It is mutually exclusive with inline session configuration. The host
// owns provisioning, authorization and durable deletion/reconciliation.
StoredAgentID string
// TranscriptionMode selects AssemblyAI native speed versus accuracy.
// Empty preserves the provider default; other providers do not map it.
TranscriptionMode TranscriptionMode
// FallbackModel is tried when the primary Model's Connect fails. Empty
// disables the fallback. Typical pairing in 2026: a preview model as
// Model + the last GA model as FallbackModel, so transient preview
// outages don't take down a Voice Agent deployment.
FallbackModel string
APIKey string
// BearerToken mints a short-lived bearer token for the connection when
// the host authenticates with an identity provider (Microsoft Entra on
// Foundry) instead of a static key. Providers that support it call it at
// dial time and send "Authorization: Bearer <token>"; when set it wins
// over APIKey, and providers that require a credential accept either.
// The framework never acquires tokens itself.
BearerToken func(ctx context.Context) (string, error)
// Endpoint overrides the provider's default WebSocket base URL. Providers
// that speak a shared wire protocol from different hosts use it — e.g.
// Microsoft Foundry serves the OpenAI Realtime protocol from
// wss://<account-host>/openai/v1/realtime. Empty keeps the provider's
// built-in default endpoint. The model/deployment query parameter is
// appended by the provider; do not include it here.
Endpoint string
Voice string // Voice name
FrameworkPrompt string
RefinementPrompt string
VocabularyHint string
Locale string
// Region is the Google Cloud region the caller's API key / project is
// pinned to (e.g. "europe-west3", "us-central1"). Only the opt-in Gemini
// Live provider reads it; other providers ignore it. For Gemini Live (as
// of May 2026) the API
// exposes a single global WebSocket endpoint, so this field does NOT
// redirect traffic — it is logged at connect time for compliance evidence
// (byok.key_updated audit event) and reserved for future regional routing
// once Google publishes per-region hostnames. Data residency is controlled
// at the Google Cloud project level; both the project region AND this field
// must agree for audit records to be accurate.
// See docs/compliance/byok-gemini-region-pinning.md.
Region string
Policies LivePolicies
Tools []ToolDefinition
Workflow *WorkflowConfig
Speaker speaker.Options
Options provideropts.Values
ProviderOptions provideropts.Values
}
LiveConfig configures a real-time session.
func DefaultLiveConfigForProvider ¶ added in v0.47.0
func DefaultLiveConfigForProvider(providerOrProfile string) (LiveConfig, bool)
DefaultLiveConfigForProvider returns a provider/profile/model tuple suitable for constructing an embedded Voice Agent session. Callers still supply API keys, prompts, tools, and policies.
type LiveEndpointReporter ¶ added in v0.61.33
type LiveEndpointReporter interface {
EndpointURL() string
}
LiveEndpointReporter is implemented by providers that can report the endpoint they dial. Connect-time observability only — the reported URL must never carry credentials; providerEndpointForLog additionally strips any query string so tokens passed as query parameters cannot leak into logs.
type LiveEventType ¶ added in v0.47.0
type LiveEventType string
LiveEventType is the provider-neutral meaning of a LiveMessage. Providers set it when translating native frames; InferLiveEventTypes derives it from the populated fields otherwise.
const ( // LiveEventSessionReady announces that the session is configured and // accepts input. The built-in providers do not emit it; speechkit-server // surfaces it on its WebSocket protocol. LiveEventSessionReady LiveEventType = "session_ready" // LiveEventInputPartial carries an interim user transcript. LiveEventInputPartial LiveEventType = "input_partial" // LiveEventInputFinal carries a final user transcript segment. LiveEventInputFinal LiveEventType = "input_final" // LiveEventOutputAudio carries a chunk of agent audio. LiveEventOutputAudio LiveEventType = "output_audio" // LiveEventOutputText carries agent text or an output transcript. LiveEventOutputText LiveEventType = "output_text" // LiveEventToolCall carries host-side tool calls. LiveEventToolCall LiveEventType = "tool_call" // LiveEventToolResultAck confirms that a tool result reached the model; // speechkit-server emits it for server-executed tools. LiveEventToolResultAck LiveEventType = "tool_result_ack" // LiveEventInterrupted reports user barge-in. LiveEventInterrupted LiveEventType = "interrupted" // LiveEventTurnEnd marks the end of a model turn. LiveEventTurnEnd LiveEventType = "turn_end" // LiveEventTurnFailed reports a failed turn without ending the session. LiveEventTurnFailed LiveEventType = "turn_failed" // LiveEventSessionResumable reports that the session can be resumed after // a reconnect. LiveEventSessionResumable LiveEventType = "session_resumable" // LiveEventSessionEnd reports that the provider is ending the session. LiveEventSessionEnd LiveEventType = "session_end" )
Event types carried in LiveMessage.EventType and LiveMessage.EventTypes.
func InferLiveEventTypes ¶ added in v0.47.0
func InferLiveEventTypes(msg *LiveMessage) []LiveEventType
InferLiveEventTypes returns the provider-neutral event meanings represented by a LiveMessage. Providers should set EventType/EventTypes themselves when translating native frames; this helper gives custom providers and tests the same fallback semantics.
type LiveInstructionUpdater ¶
type LiveInstructionUpdater interface {
UpdateInstructions(ctx context.Context, cfg LiveConfig) error
}
LiveInstructionUpdater is optionally implemented by providers that can refresh active host instructions without treating the update as a user turn.
type LiveMessage ¶
type LiveMessage struct {
EventType LiveEventType // Provider-neutral event type for hosts that need precise routing.
EventTypes []LiveEventType // All provider-neutral event meanings when a provider combines multiple events in one frame.
ProviderMetadata map[string]any // Optional provider-native metadata for debugging and advanced hosts.
Audio []byte // PCM audio chunk (24kHz 16-bit mono)
Text string // Text transcript (may be partial or empty)
Done bool // True when the model's turn is complete
// TurnError reports a failed turn while leaving the session usable. It must
// contain only safe public guidance; transport/session failures are returned
// from Receive instead. Hosts may inspect a Code() string method for routing.
TurnError error
// Transcription fields (populated when transcription is enabled).
InputTranscript string // User speech transcribed by server
InputTranscriptDone bool // True when input transcription segment is final
InputSpeakerLabel string // Optional diarized speaker label for input transcript segments
InputPersonID string // Optional known person id for input transcript segments
InputDisplayName string // Optional known display name for input transcript segments
InputSpeakerConfidence float64 // Optional speaker-label confidence
OutputTranscript string // Model speech transcribed by server
OutputTranscriptDone bool // True when output transcription segment is final
ToolCalls []ToolCall
ToolCallCancellationIDs []string
Interrupted bool // True when user interrupted model (barge-in)
GoAway bool // True when server signals imminent session end
SessionResumable bool // True when the provider indicates reconnect/resume is possible.
}
LiveMessage is a message received from the real-time model.
func NormalizeMessageEvents ¶ added in v0.64.3
func NormalizeMessageEvents(msg *LiveMessage, providerEvent string) *LiveMessage
NormalizeMessageEvents completes the event metadata of msg in place and returns it: EventTypes is inferred with InferLiveEventTypes when empty, EventType defaults to the first entry, and a non-empty providerEvent (the native event name) is recorded as ProviderMetadata["provider_event"] unless the provider already set one. A nil msg is returned unchanged.
type LiveModelDescriptor ¶ added in v0.47.0
type LiveModelDescriptor struct {
Provider string `json:"provider"`
ModelID string `json:"modelId"`
Name string `json:"name"`
Lifecycle framework.ModelLifecycle `json:"lifecycle"`
Default bool `json:"default,omitempty"`
Recommended bool `json:"recommended,omitempty"`
SourceURL string `json:"sourceUrl"`
}
LiveModelDescriptor is one realtime model a provider advertises, projected from the framework model catalog. Default marks the model ProviderDescriptor.DefaultModel returns, Recommended the catalog's preferred pick, and SourceURL the vendor page that evidences the entry.
type LivePolicies ¶
type LivePolicies struct {
EnableInputAudioTranscription bool
EnableOutputAudioTranscription bool
EnableAffectiveDialog bool
Thinking ThinkingPolicy
ContextCompression ContextCompressionPolicy
ActivityDetection ActivityDetectionPolicy
}
LivePolicies configures Google Live API features that shape Voice Agent behavior.
type LiveProvider ¶
type LiveProvider interface {
// Connect establishes a WebSocket session to the real-time model.
Connect(ctx context.Context, cfg LiveConfig) error
// SendAudio streams PCM audio chunks to the model.
// Format: 16-bit signed int, little-endian, mono, 16kHz.
SendAudio(chunk []byte) error
// SendAudioStreamEnd signals that microphone input for the current turn ended.
SendAudioStreamEnd() error
// Receive blocks until the next server message arrives.
// Returns audio chunks and/or text from the model.
Receive(ctx context.Context) (*LiveMessage, error)
// SendText injects a text prompt into the session (for idle reminders).
SendText(text string) error
// SendToolResponse sends the result of a host-side tool invocation back to the model.
SendToolResponse(response ToolResponse) error
// Close terminates the WebSocket session.
Close() error
// Name returns the provider identifier.
Name() string
}
LiveProvider abstracts a real-time audio-to-audio model connection.
type LiveReconnector ¶
LiveReconnector is an optional interface for providers that support session reconnection.
type LiveSessionCapabilities ¶ added in v0.47.0
type LiveSessionCapabilities interface {
SessionCapabilities() SessionCapabilities
}
LiveSessionCapabilities is implemented by providers that can report the profile, model and capabilities of their sessions. The built-in providers derive it from SessionCapabilitiesForProvider.
type ModelLifecyclePolicy ¶ added in v0.47.0
type ModelLifecyclePolicy string
ModelLifecyclePolicy limits which model lifecycle stages ResolveProviderIntent may select; see ProviderSelectionPolicy.
const ( // ModelLifecycleAny accepts GA, preview, legacy and deprecated models. ModelLifecycleAny ModelLifecyclePolicy = "any" // ModelLifecyclePreferGA accepts GA and preview models; legacy and // deprecated ones also need [ProviderSelectionPolicy.AllowLegacy]. ModelLifecyclePreferGA ModelLifecyclePolicy = "prefer_ga" // ModelLifecycleRequireGA accepts GA models only. ModelLifecycleRequireGA ModelLifecyclePolicy = "require_ga" )
Lifecycle policies. The empty value behaves like ModelLifecyclePreferGA except that preview models also need ProviderSelectionPolicy.AllowPreview.
type ProviderDescriptor ¶ added in v0.47.0
type ProviderDescriptor struct {
Provider string `json:"provider"`
DisplayName string `json:"displayName"`
ProfileID string `json:"profileId"`
Capabilities []LiveCapabilityFlag `json:"capabilities"`
Models []LiveModelDescriptor `json:"models,omitempty"`
SupportedLocales []string `json:"supportedLocales,omitempty"`
NativeOptions []provideropts.OptionID `json:"nativeOptions,omitempty"`
AuthRequirement string `json:"authRequirement,omitempty"`
Transport string `json:"transport,omitempty"`
EvidenceURL string `json:"evidenceUrl,omitempty"`
OptIn bool `json:"optIn,omitempty"`
}
ProviderDescriptor is the public catalog entry for a realtime provider: its canonical id and public profile id, advertised capabilities and models, accepted locales ("*" for any), the provider-native option ids it honours, how it authenticates ("api_key") and connects ("websocket"), and the vendor documentation that evidences the claims. OptIn marks a provider that ResolveProviderIntent only considers when the intent names it (provider, profile, model, or a preferred provider); it is never an implicit pick.
func DefaultProviderDescriptors ¶ added in v0.47.0
func DefaultProviderDescriptors() []ProviderDescriptor
DefaultProviderDescriptors returns the public live-provider catalog for embedders that want to switch providers by name/profile/model at runtime.
func FindProviderDescriptor ¶ added in v0.47.0
func FindProviderDescriptor(providerOrProfile string) (ProviderDescriptor, bool)
FindProviderDescriptor resolves provider ids, provider aliases, and profile ids to the canonical public descriptor.
func (ProviderDescriptor) DefaultModel ¶ added in v0.47.0
func (d ProviderDescriptor) DefaultModel() (LiveModelDescriptor, bool)
DefaultModel returns the provider's default live model. If no model is explicitly marked as default, it falls back to the first advertised model.
func (ProviderDescriptor) HasCapability ¶ added in v0.47.0
func (d ProviderDescriptor) HasCapability(flag LiveCapabilityFlag) bool
HasCapability reports whether this provider advertises a capability.
type ProviderFallback ¶ added in v0.47.0
type ProviderFallback struct {
Kind ProviderFallbackKind `json:"kind"`
Provider string `json:"provider"`
ProfileID string `json:"profileId,omitempty"`
Model string `json:"model,omitempty"`
ModelLifecycle framework.ModelLifecycle `json:"modelLifecycle,omitempty"`
Reason string `json:"reason,omitempty"`
MissingRequiredCapabilities []LiveCapabilityFlag `json:"missingRequiredCapabilities,omitempty"`
MissingRequiredOptions []provideropts.OptionID `json:"missingRequiredOptions,omitempty"`
AuthRequirement string `json:"authRequirement,omitempty"`
Transport string `json:"transport,omitempty"`
EvidenceURL string `json:"evidenceUrl,omitempty"`
}
ProviderFallback is an alternative to the selected plan. Kind says how it relates to the selection; the other fields identify the provider and model, its authentication and transport, and the evidence URL.
type ProviderFallbackKind ¶ added in v0.47.0
type ProviderFallbackKind string
ProviderFallbackKind classifies a ProviderFallback or ProviderRejection relative to the selected plan.
const ( // FallbackKindSameProviderModel is another model of the same provider. FallbackKindSameProviderModel ProviderFallbackKind = "same_provider_model" // FallbackKindCrossProvider is a different realtime provider. FallbackKindCrossProvider ProviderFallbackKind = "cross_provider" // FallbackKindCascaded is the local STT -> LLM -> TTS pipeline. FallbackKindCascaded ProviderFallbackKind = "cascaded" // FallbackKindCapabilityMissing marks a rejection caused by missing // required capabilities or options. FallbackKindCapabilityMissing ProviderFallbackKind = "capability_missing" )
Fallback kinds.
type ProviderIntent ¶ added in v0.47.0
type ProviderIntent struct {
Mode string `json:"mode,omitempty"`
Provider string `json:"provider,omitempty"`
ProfileID string `json:"profileId,omitempty"`
Model string `json:"model,omitempty"`
RequiredCapabilities []LiveCapabilityFlag `json:"requiredCapabilities,omitempty"`
PreferredCapabilities []LiveCapabilityFlag `json:"preferredCapabilities,omitempty"`
Requirements []CapabilityRequirement `json:"requirements,omitempty"`
RequiredOptions []provideropts.OptionID `json:"requiredOptions,omitempty"`
PreferredOptions []provideropts.OptionID `json:"preferredOptions,omitempty"`
Locale string `json:"locale,omitempty"`
LanguageHints []string `json:"languageHints,omitempty"`
PrivacyRedaction bool `json:"privacyRedaction,omitempty"`
ResumePreferred bool `json:"resumePreferred,omitempty"`
LatencyProfile LatencyProfile `json:"latencyProfile,omitempty"`
SelectionPolicy ProviderSelectionPolicy `json:"selectionPolicy,omitempty"`
}
ProviderIntent describes what a host needs from a realtime session so ResolveProviderIntent can choose a provider and model. Provider, ProfileID and Model pin candidates when set; Required* fields must be satisfied while Preferred* fields only raise the score, and Requirements is folded into those lists. PrivacyRedaction requires LiveCapabilityPrivacyRedaction, ResumePreferred prefers LiveCapabilitySessionResume, and LanguageHints prefers native language hints. Locale excludes descriptors that list locales without it. Mode defaults to voice_agent, the only mode the catalog serves.
type ProviderIntentError ¶ added in v0.47.0
type ProviderIntentError struct {
Intent ProviderIntent `json:"intent"`
MissingRequiredCapabilities []LiveCapabilityFlag `json:"missingRequiredCapabilities,omitempty"`
MissingRequiredOptions []provideropts.OptionID `json:"missingRequiredOptions,omitempty"`
Fallbacks []ProviderFallback `json:"fallbacks,omitempty"`
RejectedProviders []ProviderRejection `json:"rejectedProviders,omitempty"`
}
ProviderIntentError is returned by ResolveProviderIntent when no descriptor satisfies the intent. It lists the required capabilities and options that no candidate provided and every rejected candidate with its reason; Fallbacks is currently never populated. It unwraps to ErrNoMatchingProvider.
func (*ProviderIntentError) Error ¶ added in v0.47.0
func (e *ProviderIntentError) Error() string
func (*ProviderIntentError) Unwrap ¶ added in v0.47.0
func (e *ProviderIntentError) Unwrap() error
type ProviderRejection ¶ added in v0.47.0
type ProviderRejection struct {
Provider string `json:"provider"`
ProfileID string `json:"profileId,omitempty"`
Model string `json:"model,omitempty"`
ModelLifecycle framework.ModelLifecycle `json:"modelLifecycle,omitempty"`
FallbackKind ProviderFallbackKind `json:"fallbackKind,omitempty"`
Reason string `json:"reason"`
MissingRequiredCapabilities []LiveCapabilityFlag `json:"missingRequiredCapabilities,omitempty"`
MissingRequiredOptions []provideropts.OptionID `json:"missingRequiredOptions,omitempty"`
AuthRequirement string `json:"authRequirement,omitempty"`
Transport string `json:"transport,omitempty"`
EvidenceURL string `json:"evidenceUrl,omitempty"`
UnsupportedLocale string `json:"unsupportedLocale,omitempty"`
}
ProviderRejection explains why one descriptor was excluded from a plan: the model it would have used and its lifecycle, the reason, and the missing capabilities, options or locale when those caused it.
type ProviderSelectionPolicy ¶ added in v0.47.0
type ProviderSelectionPolicy struct {
PreferredProviders []string `json:"preferredProviders,omitempty"`
AllowPreview bool `json:"allowPreview,omitempty"`
AllowLegacy bool `json:"allowLegacy,omitempty"`
ModelLifecycle ModelLifecyclePolicy `json:"modelLifecycle,omitempty"`
}
ProviderSelectionPolicy tunes how ResolveProviderIntent filters and ranks candidates. PreferredProviders (ids or aliases, best first) add a decreasing score bonus; ModelLifecycle, AllowPreview and AllowLegacy gate preview, legacy and deprecated models as described on ModelLifecyclePolicy.
type ResolvedLiveOptions ¶ added in v0.45.0
type ResolvedLiveOptions struct {
Locale string
Voice string
ContextPrompt string
LanguageHints []string
Keyterms []string
ReasoningEffort string
Resume bool
TurnDetection bool
TurnDetectionSource provideropts.ValueSource
EndpointingMs int
EndpointingSource provideropts.ValueSource
Effective provideropts.EffectiveOptions
}
ResolvedLiveOptions is the per-session view of the provider option layers after ResolveLiveOptions: the effective locale, voice, context prompt, language hints, key terms, reasoning effort and resume flag, plus the turn detection and endpointing choices with the layer that set them, so a provider can tell an explicit setting from its own default. EndpointingMs is in milliseconds and zero when unset. Effective keeps the full provideropts.EffectiveOptions, including unsupported-option reports.
func ResolveLiveOptions ¶ added in v0.45.0
func ResolveLiveOptions(provider, profileID string, cfg LiveConfig, providerDefaults, providerOverrides provideropts.Values) ResolvedLiveOptions
ResolveLiveOptions merges the option layers for provider's voice-agent manifest, lowest precedence first: providerDefaults, cfg.Options, providerOverrides merged with cfg.ProviderOptions, and a request layer built from cfg.Locale, cfg.Voice and, when no key terms were configured elsewhere, cfg.VocabularyHint split into terms. profileID is echoed into the result. Options the provider cannot honour are logged at debug level and listed in Effective.Unsupported; a provider without a manifest gets an empty one.
func (ResolvedLiveOptions) HasEndpointingOverride ¶ added in v0.45.0
func (r ResolvedLiveOptions) HasEndpointingOverride() bool
HasEndpointingOverride reports whether endpointing was set by a host layer rather than left unset or to the provider default.
func (ResolvedLiveOptions) HasTurnDetectionOverride ¶ added in v0.45.0
func (r ResolvedLiveOptions) HasTurnDetectionOverride() bool
HasTurnDetectionOverride reports whether turn detection was set by a host layer (global, provider or request) rather than left unset or to the provider default.
type ResolvedProviderPlan ¶ added in v0.47.0
type ResolvedProviderPlan struct {
Provider string `json:"provider"`
ProfileID string `json:"profileId"`
Model string `json:"model"`
Descriptor ProviderDescriptor `json:"descriptor"`
ModelDescriptor LiveModelDescriptor `json:"modelDescriptor"`
SelectionReason string `json:"selectionReason,omitempty"`
SelectedFallbackKind ProviderFallbackKind `json:"selectedFallbackKind,omitempty"`
Fallbacks []ProviderFallback `json:"fallbacks,omitempty"`
RejectedProviders []ProviderRejection `json:"rejectedProviders,omitempty"`
MatchedRequiredCapabilities []LiveCapabilityFlag `json:"matchedRequiredCapabilities,omitempty"`
MatchedPreferredCapabilities []LiveCapabilityFlag `json:"matchedPreferredCapabilities,omitempty"`
UnsupportedPreferredCapabilities []LiveCapabilityFlag `json:"unsupportedPreferredCapabilities,omitempty"`
MatchedRequiredOptions []provideropts.OptionID `json:"matchedRequiredOptions,omitempty"`
MatchedPreferredOptions []provideropts.OptionID `json:"matchedPreferredOptions,omitempty"`
UnsupportedPreferredOptions []provideropts.OptionID `json:"unsupportedPreferredOptions,omitempty"`
AuthRequirement string `json:"authRequirement,omitempty"`
Transport string `json:"transport,omitempty"`
LatencyProfile LatencyProfile `json:"latencyProfile,omitempty"`
}
ResolvedProviderPlan is the result of ResolveProviderIntent: the chosen provider, profile and model with their descriptors, why they were chosen (SelectionReason, SelectedFallbackKind), which requested capabilities and options matched or are unsupported, ranked alternatives in Fallbacks, and the candidates that were rejected.
func ResolveProviderIntent ¶ added in v0.47.0
func ResolveProviderIntent(intent ProviderIntent, descriptors []ProviderDescriptor) (ResolvedProviderPlan, error)
ResolveProviderIntent picks the provider and model that best satisfy intent from descriptors; nil or empty uses DefaultProviderDescriptors. A candidate must match the requested provider or profile, advertise the requested (or its default) model within the lifecycle policy, support the locale, and provide every required capability and option. Candidates are scored by an explicit provider or profile match, the default, recommended and GA flags of the model, position in PreferredProviders, and each matched preferred capability and option; ties keep descriptor order. ProviderDescriptor.OptIn providers are skipped unless the intent names them. When nothing qualifies it returns a *ProviderIntentError.
func (ResolvedProviderPlan) LiveConfig ¶ added in v0.47.0
func (p ResolvedProviderPlan) LiveConfig() LiveConfig
LiveConfig converts the plan into a LiveConfig with Provider, ProfileID and Model set and FallbackModel taken from the first FallbackKindSameProviderModel fallback. Credentials, prompts, tools and policies are left to the caller.
func (ResolvedProviderPlan) String ¶ added in v0.47.0
func (p ResolvedProviderPlan) String() string
type ResumeHandle ¶ added in v0.64.3
type ResumeHandle struct {
// contains filtered or unexported fields
}
ResumeHandle stores a realtime session-resumption handle with a time-to- live and at-rest protection. On Windows the ciphertext is produced by DPAPI (CryptProtectData, user-scope) so a memory dump taken hours later cannot be replayed against the same session. On other platforms the handle is held in memory without encryption (there is no equivalent process-scoped primitive in the Go standard library) but the TTL still applies.
func NewResumeHandle ¶ added in v0.64.3
func NewResumeHandle() *ResumeHandle
NewResumeHandle returns an empty handle whose TTL is measured against the wall clock.
func (*ResumeHandle) Clear ¶ added in v0.64.3
func (h *ResumeHandle) Clear()
Clear wipes any stored handle.
func (*ResumeHandle) Get ¶ added in v0.64.3
func (h *ResumeHandle) Get() string
Get returns the cleartext handle if present and not expired. Expired handles are discarded on read. An empty return value means "no handle available".
func (*ResumeHandle) Set ¶ added in v0.64.3
func (h *ResumeHandle) Set(raw string)
Set replaces the stored handle. An empty input clears it.
func (*ResumeHandle) SetLogger ¶ added in v0.74.0
func (h *ResumeHandle) SetLogger(l *slog.Logger)
SetLogger routes this handle's diagnostics to l. Nil restores the slog.Default() fallback.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session manages a Voice Agent conversation.
func NewSession ¶
func NewSession(provider LiveProvider, callbacks Callbacks) *Session
NewSession creates a Voice Agent session with the given provider.
Example ¶
ExampleNewSession drives a realtime dialogue through a Session: Start connects the provider, SendText (or SendAudio) feeds the model, and transcripts, audio and state changes arrive through Callbacks.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/kombifyio/SpeechKit/pkg/speechkit/voiceagent/live"
)
// echoLive is an in-memory live.LiveProvider. Real hosts use a provider from
// voiceagent/live/openai, deepgram, assemblyai, or allproviders.
type echoLive struct{ out chan *live.LiveMessage }
func (p *echoLive) Connect(context.Context, live.LiveConfig) error { return nil }
func (p *echoLive) SendAudio([]byte) error { return nil }
func (p *echoLive) SendAudioStreamEnd() error { return nil }
func (p *echoLive) SendToolResponse(live.ToolResponse) error { return nil }
func (p *echoLive) Close() error { return nil }
func (p *echoLive) Name() string { return "echo" }
func (p *echoLive) SendText(text string) error {
p.out <- &live.LiveMessage{OutputTranscript: "echo: " + text, OutputTranscriptDone: true, Done: true}
return nil
}
func (p *echoLive) Receive(ctx context.Context) (*live.LiveMessage, error) {
select {
case m := <-p.out:
return m, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// ExampleNewSession drives a realtime dialogue through a Session: Start
// connects the provider, SendText (or SendAudio) feeds the model, and
// transcripts, audio and state changes arrive through Callbacks.
func main() {
provider := &echoLive{out: make(chan *live.LiveMessage, 4)}
heard := make(chan string, 1)
session := live.NewSession(provider, live.Callbacks{
OnOutputTranscript: func(text string, done bool) {
if done {
heard <- text
}
},
})
if err := session.Start(context.Background(), live.LiveConfig{Locale: "en"}, live.DefaultIdleConfig()); err != nil {
log.Fatal(err)
}
defer session.Stop()
if err := session.SendText("hello"); err != nil {
log.Fatal(err)
}
select {
case text := <-heard:
fmt.Println(text)
case <-time.After(5 * time.Second):
log.Fatal("no answer")
}
}
Output: echo: hello
func (*Session) AdvanceWorkflowStep ¶
AdvanceWorkflowStep moves a configured local workflow to its next step and updates the active provider instructions. It returns nil when no workflow is active or the workflow has already completed.
func (*Session) CurrentState ¶
CurrentState returns the session's current State.
func (*Session) EndAudioStream ¶
EndAudioStream tells the live provider that the current microphone stream ended.
func (*Session) ProviderName ¶
ProviderName returns the LiveProvider.Name of the session's provider, or "" for a nil session or provider.
func (*Session) SendAgentProgress ¶ added in v0.53.0
SendAgentProgress delivers a trusted progress line from a long-running host-side tool as a host prompt. It is a no-op unless the session is listening: a progress line must never interrupt the user speaking or the model answering. Returns true when the prompt was accepted and sent.
func (*Session) SendToolResponse ¶
func (s *Session) SendToolResponse(response ToolResponse) error
SendToolResponse forwards the result of a host-side tool invocation to the model.
func (*Session) SendUntrustedToolOutput ¶ added in v0.74.0
SendUntrustedToolOutput delivers output produced by an external tool (for example the coding agent behind "Call GPT") to the model. Unlike Session.SendAgentProgress, the payload is NOT a trusted host prompt: it is wrapped in per-message delimiters with an explicit instruction to treat it as data only, and delimiter look-alikes inside the payload are neutralised. lead is a short host-authored line placed outside the delimiters (for example "GPT is done"). Delivery follows the same rule as SendAgentProgress: a no-op unless the session is listening. Returns true when the text was accepted and sent.
func (*Session) SetLogger ¶ added in v0.74.0
SetLogger routes this session's diagnostics to l. Nil restores the slog.Default() fallback. Safe to call at any time.
func (*Session) Shutdown ¶ added in v0.74.0
Shutdown deactivates the session and waits until the provider connection is closed and the receive loop has exited, or ctx is done. It is idempotent and safe for concurrent use: every caller waits for the same teardown. It returns the provider close error, joined with ctx.Err() when ctx expired first. A session that is not active returns nil immediately.
func (*Session) Start ¶
func (s *Session) Start(ctx context.Context, cfg LiveConfig, idleCfg IdleConfig) error
Start activates the Voice Agent session.
func (*Session) Stop ¶
func (s *Session) Stop()
Stop deactivates the Voice Agent session. It waits at most DefaultStopCloseTimeout for provider.Close and for the receive loop to exit, so a hung websocket handshake cannot wedge the caller. Do not call Stop from inside a Callbacks handler that runs on the receive loop unless you accept the bounded wait; use a goroutine there instead.
func (*Session) StopWithTimeout ¶ added in v0.60.41
StopWithTimeout is Stop with an explicit bound covering provider.Close and the receive-loop exit. A zero or negative timeout waits without a deadline (tests and operators only).
type SessionCapabilities ¶ added in v0.47.0
type SessionCapabilities struct {
Provider string `json:"provider,omitempty"`
ProfileID string `json:"profileId,omitempty"`
Model string `json:"model,omitempty"`
Capabilities []LiveCapabilityFlag `json:"capabilities,omitempty"`
ProviderMetadata map[string]any `json:"providerMetadata,omitempty"`
}
SessionCapabilities is a provider's self-description for hosts: canonical provider id, profile, model and capability flags, plus optional provider-native metadata.
func SessionCapabilitiesForProvider ¶ added in v0.64.3
func SessionCapabilitiesForProvider(provider string) SessionCapabilities
SessionCapabilitiesForProvider builds the SessionCapabilities a built-in provider reports: the profile, default model and capability flags of the catalog descriptor for provider (an id, alias or profile id). An unknown provider yields only the normalized provider id. The flags are copied, so callers may modify the result.
type StartSensitivity ¶
type StartSensitivity string
StartSensitivity controls how aggressively automatic activity detection commits speech start.
const ( StartSensitivityLow StartSensitivity = "low" StartSensitivityMedium StartSensitivity = "medium" StartSensitivityHigh StartSensitivity = "high" )
Start sensitivities for ActivityDetectionPolicy: high commits a speech start earliest (OpenAI Realtime maps it to the lowest VAD threshold), low latest.
type State ¶
type State string
State represents the current state of a Voice Agent session.
const ( // StateInactive means no session is running. StateInactive State = "inactive" // StateConnecting means Start is dialing the provider. StateConnecting State = "connecting" // StateListening means the session waits for user speech or text. StateListening State = "listening" // StateProcessing means the user turn ended and the model has not yet // produced audio. StateProcessing State = "processing" // StateSpeaking means model audio is being delivered to the host. StateSpeaking State = "speaking" // StateRecovering means the provider announced a session end (GoAway) // and a reconnect is in progress. StateRecovering State = "recovering" // StateDeactivating means Stop or error cleanup is closing the provider. StateDeactivating State = "deactivating" )
Session states as reported through Callbacks.OnStateChange. A session starts and ends in StateInactive.
type ThinkingLevel ¶
type ThinkingLevel string
ThinkingLevel controls how much deliberate reasoning a provider should spend.
const ( ThinkingLevelOff ThinkingLevel = "off" ThinkingLevelLow ThinkingLevel = "low" ThinkingLevelMedium ThinkingLevel = "medium" ThinkingLevelHigh ThinkingLevel = "high" )
Thinking levels for ThinkingPolicy, from no deliberate reasoning (off) to the most (high).
type ThinkingPolicy ¶
type ThinkingPolicy struct {
Enabled bool
IncludeThoughts bool
ThinkingBudget int32
ThinkingLevel ThinkingLevel
}
ThinkingPolicy defines optional provider thinking behavior.
type ToolBehavior ¶
type ToolBehavior string
ToolBehavior controls whether the model waits for a tool result.
const ( // ToolBehaviorUnspecified keeps the provider default. ToolBehaviorUnspecified ToolBehavior = "" // ToolBehaviorBlocking makes the model wait for the [ToolResponse] before // it continues the turn. ToolBehaviorBlocking ToolBehavior = "blocking" // ToolBehaviorNonBlocking lets the model keep talking; the result is // reintroduced according to [ToolResponse.Scheduling]. ToolBehaviorNonBlocking ToolBehavior = "non_blocking" )
Tool behaviours for ToolDefinition.
type ToolDefinition ¶
type ToolDefinition struct {
Name string
Description string
ParametersJSONSchema map[string]any
ResponseJSONSchema map[string]any
Behavior ToolBehavior
}
ToolDefinition exposes a host-side action the Voice Agent may call.
type ToolResponse ¶
type ToolResponse struct {
ID string
Name string
Response map[string]any
Scheduling ToolResponseScheduling
WillContinue *bool
}
ToolResponse resolves a previously emitted tool call.
type ToolResponseScheduling ¶
type ToolResponseScheduling string
ToolResponseScheduling controls how a non-blocking tool result is reintroduced into the conversation.
const ( // ToolResponseSchedulingUnspecified keeps the provider default. ToolResponseSchedulingUnspecified ToolResponseScheduling = "" // ToolResponseSchedulingSilent adds the result to the conversation // without prompting a response. ToolResponseSchedulingSilent ToolResponseScheduling = "silent" // ToolResponseSchedulingWhenIdle delivers the result once the model has // finished its current output. ToolResponseSchedulingWhenIdle ToolResponseScheduling = "when_idle" // ToolResponseSchedulingInterrupt interrupts the current output to // deliver the result immediately. ToolResponseSchedulingInterrupt ToolResponseScheduling = "interrupt" )
Scheduling values for the result of a non-blocking tool.
type TranscriptionMode ¶ added in v0.75.8
type TranscriptionMode string
TranscriptionMode is the AssemblyAI native speech recognition profile.
const ( TranscriptionBalanced TranscriptionMode = "balanced" TranscriptionMinLatency TranscriptionMode = "min_latency" TranscriptionMaxAccuracy TranscriptionMode = "max_accuracy" )
Supported native transcription modes. Empty uses the provider default.
func (TranscriptionMode) Valid ¶ added in v0.75.8
func (m TranscriptionMode) Valid() bool
Valid reports whether the mode is supported, including the default.
type TurnCoverage ¶
type TurnCoverage string
TurnCoverage controls how the live API builds a user turn from incoming activity.
const ( // TurnCoverageUnspecified keeps the provider default. TurnCoverageUnspecified TurnCoverage = "" // TurnCoverageTurnIncludesOnlyActivity builds the user turn from detected // activity only, dropping the silence around it. TurnCoverageTurnIncludesOnlyActivity TurnCoverage = "turn_includes_only_activity" // TurnCoverageTurnIncludesAllInput builds the user turn from all input // since the previous turn, silence included. TurnCoverageTurnIncludesAllInput TurnCoverage = "turn_includes_all_input" // TurnCoverageTurnIncludesAudioActivity restricts the user turn to // detected audio activity. TurnCoverageTurnIncludesAudioActivity TurnCoverage = "turn_includes_audio_activity" )
Turn coverage values for ActivityDetectionPolicy. They follow the Google Live API vocabulary and are honoured only by providers that expose the setting.
type WorkflowConfig ¶
type WorkflowConfig struct {
SequenceID string
Completion string
MaxTurns int
BasePrompt string
Steps []WorkflowStep
// InitialStep selects the first active step. Out-of-range values fall
// back to zero.
InitialStep int
}
WorkflowConfig describes a deterministic, step-based Voice Agent behavior sequence. Durations are intentionally expressed as turns instead of wall clock time so tests and local installs can exercise long moderation flows quickly.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package allproviders is the batteries-included realtime Voice Agent assembly layer: it knows every provider SpeechKit ships and resolves a provider id, alias or profile id to a live provider.
|
Package allproviders is the batteries-included realtime Voice Agent assembly layer: it knows every provider SpeechKit ships and resolves a provider id, alias or profile id to a live provider. |
|
Package assemblyai adapts the AssemblyAI Voice Agent WebSocket API (wss://agents.assemblyai.com/v1/ws) to live.LiveProvider.
|
Package assemblyai adapts the AssemblyAI Voice Agent WebSocket API (wss://agents.assemblyai.com/v1/ws) to live.LiveProvider. |
|
Package deepgram adapts the Deepgram Voice Agent API (wss://agent.deepgram.com/v1/agent/converse) to live.LiveProvider: one WebSocket carries listen (Flux or Nova STT), think (a Deepgram-managed or bring-your-own LLM) and speak (Aura-2 or Flux TTS).
|
Package deepgram adapts the Deepgram Voice Agent API (wss://agent.deepgram.com/v1/agent/converse) to live.LiveProvider: one WebSocket carries listen (Flux or Nova STT), think (a Deepgram-managed or bring-your-own LLM) and speak (Aura-2 or Flux TTS). |
|
Package foundry adapts the OpenAI Realtime provider to Microsoft Foundry.
|
Package foundry adapts the OpenAI Realtime provider to Microsoft Foundry. |
|
Package gemini adapts the Google Gemini Live API (via the google.golang.org/genai SDK) to live.LiveProvider.
|
Package gemini adapts the Google Gemini Live API (via the google.golang.org/genai SDK) to live.LiveProvider. |
|
Package livecontract provides reusable conformance checks for LiveProvider implementations.
|
Package livecontract provides reusable conformance checks for LiveProvider implementations. |
|
Package openai adapts the OpenAI Realtime WebSocket API (wss://api.openai.com/v1/realtime, GA session shape) to live.LiveProvider.
|
Package openai adapts the OpenAI Realtime WebSocket API (wss://api.openai.com/v1/realtime, GA session shape) to live.LiveProvider. |
|
Package openailive adapts OpenAI's full-duplex Live API (model gpt-live-1, WebSocket wss://api.openai.com/v1/live/sessions) to live.LiveProvider.
|
Package openailive adapts OpenAI's full-duplex Live API (model gpt-live-1, WebSocket wss://api.openai.com/v1/live/sessions) to live.LiveProvider. |
|
Package voicelive adapts the OpenAI Realtime provider to Microsoft Foundry's Voice Live API.
|
Package voicelive adapts the OpenAI Realtime provider to Microsoft Foundry's Voice Live API. |