Documentation
¶
Overview ¶
Package relayapi defines the public wire contract of the Global Speko Relay: HTTP request and response bodies, WebSocket control and event frames, SSE stream events, the normalized error envelope, response headers, and the idempotency hashing rules shared by every relay endpoint.
The package is the single source of truth for both sides of the wire: the relay edge implements these types, and the hand-authored OpenAPI/AsyncAPI documents are machine-checked against them. It deliberately depends only on the standard library so integrators can import the contract without pulling in relay internals.
Contract decisions that shape the types:
Routing is a closed tagged union. An entirely omitted routing object means {mode: auto, objective: balanced}; handlers apply that default with Routing.NormalizeDefault before validating. Mixed auto/explicit fields and unknown objectives are rejected, never silently ignored.
Errors are always {"error": {code, message, retryable, request_id}} with a closed code set. Raw provider response bodies are never forwarded to callers.
LLM response IDs are Speko-minted as resp_<request-id>. Provider response and conversation IDs never appear in output; they are captured only as content-free telemetry evidence. There is no previous_response_id anywhere in the contract: callers resend full history, including function results, on every request.
Usage split lines are mutually exclusive: cache writes and cached_input_tokens are not repeated in input_tokens and reasoning_tokens are not repeated in output_tokens, so the splits always sum to the totals. Providers that report no split report all-uncached / all-visible.
Idempotency-Key is required on every POST and on every WebSocket upgrade request. The content hash for single-part HTTP bodies covers the raw body bytes as sent; for multipart bodies it covers the decoded part payload bytes only — no part headers, no boundary bytes — concatenated in part order; for WebSocket sessions it covers the exact session.configure text-frame bytes, and later frames are intentionally outside the hash. See idempotency.go for the full contract.
Speko-Region names the Speko Router location that served a request. It is a proximity fact, not a provider data-residency guarantee.
Index ¶
- Constants
- Variables
- func AsyncAPISpecJSON() []byte
- func BidiMessageKey(payload []byte) (string, bool)
- func DecodeBidiAudio(payload []byte) (chunks []string, streamEnd bool, ok bool)
- func DefaultErrorHint(code ErrorCode) string
- func HashContent(content []byte) string
- func LiveToolType(tool json.RawMessage) string
- func OpenAPISpecJSON() []byte
- func ResponseID(requestID string) string
- func TerminalSSEEvent(name string) bool
- func ThinkingLevels() []string
- func ValidCommitID(id string) bool
- func ValidSTTLanguageTag(tag string) bool
- func ValidateContentHash(value string) error
- func ValidateIdempotencyKey(key string) error
- type AudioConfig
- type AudioFormat
- type BatchAudioLimits
- type BenchmarkMetadata
- type BidiAudioChunk
- type BidiSetup
- type BidiSetupConfig
- type ContentHasher
- type ContentPart
- type ErrorBody
- type ErrorCode
- type ErrorEnvelope
- type ErrorEvent
- type EvaluationAnswer
- type EvaluationLimits
- type EvaluationQuestion
- type EvaluationRequest
- type EvaluationResponse
- type EvaluationShape
- type FunctionTool
- type Item
- type ItemType
- type Kind
- type LLMRequest
- type LLMResponse
- type LiveAudioConfig
- type LiveAudioFormat
- type LiveAudioOutput
- type LiveContentPart
- type LiveDelegationConfig
- type LiveInputItem
- type LiveResponsesConfig
- type LiveSessionConfig
- type LiveSessionStart
- type MessageRole
- type Model
- type ModelBenchmark
- type ModelCapabilities
- type ModelsResponse
- type ResponseCompleted
- type ResponseCreated
- type ResponseFormat
- type ResponseFunctionCallArgumentsDelta
- type ResponseItemAdded
- type ResponseItemCompleted
- type ResponseTextDelta
- type Route
- type Routing
- type RoutingMode
- type RoutingObjective
- type S2SAudioConfig
- type S2SControlType
- type S2SEventType
- type S2SInputCommit
- type S2SInputSpeechEnded
- type S2SInputSpeechStarted
- type S2SInputTranscript
- type S2SResponseCancel
- type S2SResponseCancelled
- type S2SResponseDone
- type S2SResponseStarted
- type S2SResponseTranscriptDelta
- type S2SSessionClose
- type S2SSessionClosed
- type S2SSessionConfigure
- type S2SSessionReady
- type S2SUsageUpdated
- type STTControlType
- type STTEventType
- type STTInputCommit
- type STTOptions
- func (o *STTOptions) Diarize() bool
- func (o *STTOptions) GetKeywords() []string
- func (o *STTOptions) IdentifyLanguage() bool
- func (o *STTOptions) IsZero() bool
- func (o *STTOptions) ReduceNoise() bool
- func (o *STTOptions) TranslationTarget() string
- func (o *STTOptions) Validate() error
- func (o *STTOptions) WantsWordTimestamps() bool
- type STTSessionClose
- type STTSessionClosed
- type STTSessionConfigure
- type STTSessionReady
- type STTTranscriptDelta
- type STTTranscriptFinal
- type STTTranslation
- type STTUsageUpdated
- type SampleRateRange
- type SpeechRequest
- type StopReason
- type StreamEvent
- type TTSControlType
- type TTSEventType
- type TTSInputAppend
- type TTSInputCancel
- type TTSInputCommit
- type TTSOptions
- type TTSOptionsDecodeError
- type TTSSessionClose
- type TTSSessionClosed
- type TTSSessionConfigure
- type TTSSessionReady
- type TTSUsageUpdated
- type TTSUtteranceDone
- type TTSUtteranceStarted
- type TTSUtteranceTimings
- type TimingGranularity
- type TimingSpan
- type TranscriptDeltaSegment
- type TranscriptSegment
- type TranscriptWord
- type TranscriptionRequest
- type TranscriptionResponse
- type Usage
Constants ¶
const ( // BidiRoutePath serves the Gemini Live protocol. The first text frame MUST // be the vendor's setup message naming the model; its exact frame bytes // are the idempotency content hash, exactly as session.start is on // /v1/live. BidiRoutePath = "/v1/bidi" // BidiSetupKey is the top-level key of that first frame. BidiSetupKey = "setup" // BidiRealtimeInputKey is the media key. A realtimeInput frame that // carries audio rides the metered media path; one that carries none // (audioStreamEnd, activityStart/End, text) is forwarded as a control, and // the adapter re-checks that no audio is smuggled through that channel. BidiRealtimeInputKey = "realtimeInput" // MaxBidiSetupFrameBytes bounds the whole setup frame. It mirrors // protocol.MaxBidiSetupBytes (relayapi cannot import protocol), so a // frame this decoder accepts always fits the connector handshake: the // per-field bounds below sum well past it, and without this check a // document could pass here and be refused one hop later. MaxBidiSetupFrameBytes = 192 << 10 )
Gemini Live (BidiGenerateContent) on the Router's /v1/bidi socket.
The route is the third public speech-to-speech surface and behaves like the other two: the Router authenticates, admits, meters and forwards, and does not translate events. What differs is the FRAMING. OpenAI Realtime and GPT-Live tag every message with a "type" field; Gemini tags by the single top-level KEY of the object — `{"setup":…}`, `{"realtimeInput":…}`, `{"clientContent":…}`. Nothing in the type-tagged path (controlType, ProviderControl) can classify those, so this file carries the parallel vocabulary and the edge switches on the protocol to pick one.
const ( MaxBidiInstructionsBytes = 96 << 10 MaxBidiHistoryItems = 256 MaxBidiHistoryBytes = 256 << 10 MaxBidiTools = 64 MaxBidiToolBytes = 64 << 10 // MaxBidiSettingBytes bounds each vendor setting sub-document, including // generationConfig. 4 KiB holds because every member the vendor documents // for Live is a scalar, an enum or a short string: responseModalities, // speechConfig (voiceConfig.prebuiltVoiceConfig.voiceName, languageCode), // thinkingConfig (thinkingLevel, thinkingBudget, includeThoughts), // enableAffectiveDialog, mediaResolution, translationConfig and the // sampling scalars together stay well under 1 KiB. The only unbounded // GenerationConfig members — responseSchema and responseJsonSchema — are // ones the vendor's Live reference lists as unsupported on this surface, // so a document that needs more than 4 KiB here is not a Live document. MaxBidiSettingBytes = 4 << 10 // MaxBidiTranscriptionBytes bounds inputAudioTranscription and // outputAudioTranscription separately: unlike the other settings they // carry open-ended phrase lists (customVocabulary, adaptationPhrases) that // a caller biasing recognition toward a product catalog can legitimately // grow past 4 KiB. MaxBidiTranscriptionBytes = 16 << 10 )
Gemini Live setup bounds. They mirror the /v1/live bounds so one route cannot accept a document the other would refuse, and exist so the setup frame is validated before anything is hashed, admitted, or forwarded.
const ( EvaluationQuestionNoul = "noul" EvaluationQuestionChoice = "choice" EvaluationQuestionScore = "score" MaxChoiceOptions = 255 MaxScoreLevels = 10 )
const ( EvaluationRequestPart = "request" EvaluationAudioPart = "audio" )
Audio decisions share POST /v1/evaluations with the text evaluations above. A JSON body is a text evaluation (state + questions). A multipart body is an audio evaluation: a "request" part holding an EvaluationRequest, then an "audio" part holding one WAV (PCM s16le) clip. The question and answer types are the same noul/choice/score primitives either way, so one caller can switch decision models by changing routing alone.
const ( EvaluationInputText = "text" EvaluationInputAudio = "audio" )
Evaluation inputs a model accepts, advertised in ModelCapabilities.EvaluationInputs. A model that advertises none takes text only, which is what every evaluation model took before audio existed.
const ( // HeaderRequestID is the relay request id, also embedded in error // envelopes and Speko-minted LLM response ids. HeaderRequestID = "Speko-Request-ID" // HeaderAttemptID identifies the (possibly post-fallback) attempt that // produced the response. HeaderAttemptID = "Speko-Attempt-ID" // HeaderProvider and HeaderModel name the concrete provider decision. HeaderProvider = "Speko-Provider" HeaderModel = "Speko-Model" // HeaderRegion names the Speko Router location that served the request. // It is a proximity fact about Speko infrastructure, not a guarantee // about where the provider processed the content. HeaderRegion = "Speko-Region" )
Response headers returned by every relay endpoint. They identify the request and the concrete route decision without carrying any content.
const ( HeaderRateLimitPolicy = "RateLimit-Policy" HeaderRetryAfter = "Retry-After" HeaderDeprecation = "Deprecation" HeaderSunset = "Sunset" )
Agent-readable lifecycle and throttling headers. RateLimit-Policy follows the current IETF HTTPAPI structured-field draft; Retry-After, Deprecation, and Sunset use their standard HTTP definitions.
const ( SSEResponseCreated = "response.created" SSEResponseItemAdded = "response.item.added" SSEResponseTextDelta = "response.text.delta" SSEResponseFunctionCallArgumentsDelta = "response.function_call_arguments.delta" SSEResponseItemCompleted = "response.item.completed" SSEResponseCompleted = "response.completed" SSEError = "error" )
SSE event names for streaming POST /v1/llm/responses. The set is closed.
Every stream carries EXACTLY ONE terminal event: response.completed on success or error on failure — never both and never zero, so a client that sees the socket close without a terminal event knows the stream was truncated rather than finished. See TerminalSSEEvent.
const ( TranscriptionRequestPart = "request" TranscriptionAudioPart = "audio" )
Multipart part names for POST /v1/stt/transcriptions. The audio always travels as an uploaded part, never as a URL: the relay fetches nothing on a caller's behalf. The parts are hashed for idempotency in order — see idempotency.go.
const ( MaxSTTKeywords = 100 MaxSTTKeywordLength = 64 MaxSTTOptionProviders = 8 MaxSTTOptionKeys = 16 MaxSTTOptionStringValue = 256 )
Bounds on caller input, matching the local gateway's protocol.SttOptions.
const ( MaxTTSOptionProviders = 8 MaxTTSOptionKeys = 16 )
Bounds on caller input, matching the local gateway's protocol.TtsOptions.
const ( // RealtimeRoutePath serves the OpenAI Realtime protocol. The model is an // exact query parameter: GET /v1/realtime?model=gpt-realtime-2.1. The // idempotency content hash covers the model query value. RealtimeRoutePath = "/v1/realtime" // LiveRoutePath serves the GPT-Live protocol. The first text frame MUST be // session.start naming the model; its exact frame bytes are the // idempotency content hash. LiveRoutePath = "/v1/live" // TranslationRoutePath serves OpenAI realtime speech translation // (gpt-realtime-translate), mirroring the vendor's own // /v1/realtime/translations socket. As on /v1/realtime the model is an // exact query parameter (RealtimeModelQueryParam) and the idempotency // content hash covers exactly its value. The target language is not part // of admission: the caller names it in its first native session.update, // just as it would against the vendor. TranslationRoutePath = "/v1/realtime/translations" // QwenTranslationRoutePath serves Alibaba's LiveTranslate protocol // (alibaba.livetranslate.v1). Like /v1/realtime the model is an exact // query parameter and the idempotency content hash covers the model query // value: GET /v1/realtime/translations/qwen?model=qwen3.8-livetranslate-flash-realtime. // Every other setting — the target language above all — rides the // vendor's own session.update, which the caller sends after connecting. // The caller ends the session with the vendor's session.finish, which // the Router honours as the close: it flushes the last segment upstream // and closes once the vendor answers session.finished. // // It is a separate path from /v1/realtime because the protocol is not // conversational (no response.create, no instructions, no tools), and // from any OpenAI translation route so the two vendors' session bodies // never share a socket. QwenTranslationRoutePath = "/v1/realtime/translations/qwen" // RealtimeModelQueryParam is the /v1/realtime model selector. Both // translation routes use the same parameter. RealtimeModelQueryParam = "model" // LiveTranslateFinishType is the client event that ends a // /v1/realtime/translations/qwen session. LiveTranslateFinishType = "session.finish" // LiveSessionStartType is the type tag of the first /v1/live frame. LiveSessionStartType = "session.start" )
Public speech-to-speech routes. Every socket speaks the vendor's NATIVE JSON event protocol: the Router authenticates, admits, meters, and forwards, but it does not translate events. What the Router adds is bounded: it pins the model and audio format an admitted session may use, refuses commands that belong to another protocol, and emits its own typed error frame (the ErrorEvent shape shared with every streaming route) when the relay — not the vendor — ends a session.
Gemini Live's route and framing live in bidi.go: it is the one protocol here whose frames are keyed by their top-level field instead of a "type" tag.
const ( MaxLiveInstructionsBytes = 96 << 10 MaxLiveBackendInstructionsBytes = 96 << 10 MaxLiveHistoryItems = 256 MaxLiveHistoryBytes = 256 << 10 MaxLiveHistoryItemBytes = 32 << 10 MaxLiveTools = 64 MaxLiveToolBytes = 64 << 10 MaxLiveToolChoiceBytes = 4 << 10 MaxLiveSettingBytes = 4 << 10 MinLiveMaxOutputTokens = 16 MaxLiveMaxOutputTokens = 131_072 )
Live session bounds. They mirror the protocol package bounds (which this standard-library-only package cannot import) and exist so a session.start frame is validated before anything is hashed, admitted, or forwarded.
const ( LiveTranslateInputSampleRateHz = 16_000 LiveTranslateOutputSampleRateHz = 24_000 )
LiveTranslate audio is rate-fixed in each direction: the vendor listens to 16 kHz mono PCM16 and speaks 24 kHz mono PCM16 (Model Studio real-time translation guide). The Router pins both into the vendor session, so a caller's session.update may not move either.
const BidiOutputSampleRateHz = 24_000
BidiOutputSampleRateHz is the rate Gemini Live speaks at. Fixed by the vendor; the catalog row advertises it as the only output format.
const ContentHashPrefix = "sha256:"
ContentHashPrefix starts every canonical content hash, matching the catalog digest convention so every digest in the system reads the same way.
const ContentPartText = "text"
ContentPartText is the only content part type at launch. The part list exists so richer parts can be added later without reshaping messages.
const ErrorEventType = "error"
ErrorEventType tags the terminal error frame on STT and TTS WebSocket sessions. The name matches the SSE error event deliberately: one error vocabulary across every streaming transport.
const HeaderIdempotencyKey = "Idempotency-Key"
HeaderIdempotencyKey is required on every POST and on every WebSocket upgrade request. See idempotency.go for the content-hash and replay semantics attached to the key.
const HeaderUsageCharacters = "Speko-Usage-Characters"
HeaderUsageCharacters is the TTS-only usage header on POST /v1/tts/speech responses: the billed character count for the synthesized input. It exists because the one-shot TTS response body is a raw audio stream with no place for a usage object. There is deliberately no STT equivalent — STT usage lives in the JSON response body and in WebSocket usage events.
const MaxCommitIDLength = 64
MaxCommitIDLength bounds STTInputCommit.CommitID.
const MaxErrorHintBytes = 512
MaxErrorHintBytes bounds the caller-facing remediation text. Hints are intentionally short, single-line, relay-authored strings; provider payloads must never be copied into them.
const MaxEvaluationQuestionIDChars = 64
MaxEvaluationQuestionIDChars bounds audio question ids. Audio decision vendors key questions with restricted ids (Gemini: [A-Za-z0-9_-]{1,64}), so the audio contract fixes the common subset rather than letting one vendor reject an id another accepted.
const MaxIdempotencyKeyLength = 256
MaxIdempotencyKeyLength bounds the key so it can be persisted and indexed without truncation. The bound counts BYTES, not characters: persistence cares about storage width, so a multi-byte character spends as many of the 256 as it occupies. The specs' maxLength: 256 counts code points (JSON Schema cannot express bytes) and is therefore only an approximation; this byte bound is the normative one, stated in both spec descriptions.
const MaxS2SInstructionsBytes = 32 << 10
MaxS2SInstructionsBytes bounds the system prompt a session may carry. It rides the configure frame, and therefore the idempotency hash, so it is bounded like any other request body field rather than streamed.
const MaxSTTLanguageTagLength = 35
MaxSTTLanguageTagLength bounds a translation target. 35 characters is the longest tag RFC 5646 section 4.4.1 asks implementations to accept, far beyond any tag a vendor lists.
const ResponseFormatJSONSchema = "json_schema"
ResponseFormatJSONSchema is the only response format type. The field is an enum of one so json_object-style loose modes can be added deliberately, never by accident.
const ResponseIDPrefix = "resp_"
ResponseIDPrefix starts every LLM response id. Response ids are Speko-minted — resp_<request-id> — so output never depends on or reveals a provider's response id; provider response and conversation ids are captured only as content-free telemetry evidence.
Variables ¶
var BidiAudioSampleRates = []int{16_000}
BidiAudioSampleRates are the PCM16 input rates the Router transports for Gemini Live. The vendor listens at 16 kHz and speaks at 24 kHz — unlike GPT-Live, the two directions differ and are declared separately, so the output rate is not a caller choice on this route.
var LiveAudioSampleRates = []int{16_000, 24_000}
LiveAudioSampleRates are the PCM16 rates the Router transports for GPT-Live at launch. One format applies to both directions, as in the vendor protocol. G.711 μ-law and A-law are refused: the Router carries raw PCM.
Functions ¶
func AsyncAPISpecJSON ¶
func AsyncAPISpecJSON() []byte
AsyncAPISpecJSON returns an isolated copy of the normative AsyncAPI 2.6 document. Callers may safely hand the bytes to an HTTP response writer or mutate the returned slice without changing future results.
func BidiMessageKey ¶
BidiMessageKey returns the single top-level key of a Gemini Live frame.
The key IS the message type on this protocol, so a frame carrying none — or carrying several — is unclassifiable and refused rather than guessed at. The type-tagged routes get the same treatment from controlType.
func DecodeBidiAudio ¶
DecodeBidiAudio pulls the base64 audio payloads out of a realtimeInput frame, plus whether the caller signalled end of input audio. Unknown fields are tolerated here — unlike setup, this frame is on the hot media path and the vendor adds fields to it.
func DefaultErrorHint ¶
DefaultErrorHint returns the safe remediation used when a more specific call-site hint is unavailable. Keeping this exhaustive beside ErrorCodes guarantees older connectors can omit hint while a newer edge still emits a useful public error.
func HashContent ¶
HashContent returns the canonical content hash of a complete payload: "sha256:" followed by 64 lowercase hex digits.
func LiveToolType ¶
func LiveToolType(tool json.RawMessage) string
LiveToolType peeks the type tag of one raw tool declaration.
func OpenAPISpecJSON ¶
func OpenAPISpecJSON() []byte
OpenAPISpecJSON returns an isolated copy of the normative OpenAPI 3.1 document. Callers may safely hand the bytes to an HTTP response writer or mutate the returned slice without changing future results.
func ResponseID ¶
ResponseID mints the public LLM response id for a relay request.
func TerminalSSEEvent ¶
TerminalSSEEvent reports whether the named event ends a stream. Exactly one terminal event ends every stream.
func ThinkingLevels ¶
func ThinkingLevels() []string
ThinkingLevels are the levels a Gemini Live model can be asked for. MINIMAL is absent because the service rejects it on the only model that takes a level at all.
Spelled out here rather than imported: this package deliberately depends on the standard library alone (see doc.go), so it carries its own copy of the set protocol.ThinkingLevels() enforces plan-side. Both are EXPORTED so TestThinkingLevelsMatchProtocol can compare the sets themselves rather than a hand-written sample — a value added to one side only would otherwise slip through, and the edge would accept a level admission rejects.
func ValidCommitID ¶ added in v0.3.1
ValidCommitID reports whether id is a well-formed commit id: 1 to MaxCommitIDLength characters, each an ASCII letter or digit or one of . _ : -
func ValidSTTLanguageTag ¶
ValidSTTLanguageTag accepts the BCP-47 shape a translation target needs: a 2-3 letter primary language subtag, then hyphen-separated alphanumeric subtags of 1-8 characters, 35 characters in all. It is a shape check, not a registry lookup: whether a vendor translates INTO the language is the vendor's answer, and a tag outside its table is refused by the vendor with an error rather than served wrong. "auto" and other non-languages fail the primary-subtag rule, because a translation target cannot be detected.
func ValidateContentHash ¶
ValidateContentHash checks the canonical content hash format produced by HashContent.
func ValidateIdempotencyKey ¶
ValidateIdempotencyKey checks a caller-supplied key: non-blank and within the persistence bound. Keys are opaque; the relay imposes no format beyond that.
Types ¶
type AudioConfig ¶
type AudioConfig struct {
Encoding string `json:"encoding"`
SampleRateHz int `json:"sample_rate_hz"`
Channels int `json:"channels"`
}
AudioConfig describes raw audio on a relay stream: the output format of a TTS request, or the binary input frames of an STT stream. The bounds match the local gateway's portable media contract so a caller can move between provider-direct and relay routes without re-encoding.
func (AudioConfig) Validate ¶
func (a AudioConfig) Validate() error
Validate checks that the format is within the portable protocol bounds.
type AudioFormat ¶
type AudioFormat struct {
Encoding string `json:"encoding"`
SampleRatesHz []int `json:"sample_rates_hz,omitempty"`
SampleRateRangeHz *SampleRateRange `json:"sample_rate_range_hz,omitempty"`
Channels []int `json:"channels"`
}
AudioFormat is one exact media constraint advertised for a speech model. Exactly one of SampleRatesHz and SampleRateRangeHz must be present.
func (AudioFormat) Supports ¶
func (a AudioFormat) Supports(encoding string, sampleRateHz, channels int) bool
Supports reports whether the exact request media satisfies this format.
func (AudioFormat) Validate ¶
func (a AudioFormat) Validate() error
Validate checks that the format is concrete and unambiguous.
type BatchAudioLimits ¶
type BatchAudioLimits struct {
MaxPCMBytes int64 `json:"max_pcm_bytes,omitempty"`
MaxDurationSeconds int64 `json:"max_duration_seconds,omitempty"`
}
BatchAudioLimits are provider-path limits for a complete batch STT upload. Omitted values mean the provider path publishes no corresponding bound; deployment safety ceilings are intentionally not represented here.
type BenchmarkMetadata ¶
type BenchmarkMetadata struct {
Schema int `json:"schema"`
Source string `json:"source"`
Digest string `json:"digest"`
Language string `json:"language"`
Objective string `json:"objective"`
Path string `json:"path,omitempty"`
}
BenchmarkMetadata identifies the exact public benchmark projection used to order the model listing. Digest pins the source bytes used by the Relay.
type BidiAudioChunk ¶
type BidiAudioChunk struct {
RealtimeInput struct {
Audio *struct {
Data string `json:"data"`
MIMEType string `json:"mimeType,omitempty"`
} `json:"audio,omitempty"`
MediaChunks []struct {
Data string `json:"data"`
MIMEType string `json:"mimeType,omitempty"`
} `json:"mediaChunks,omitempty"`
AudioStreamEnd *bool `json:"audioStreamEnd,omitempty"`
} `json:"realtimeInput"`
}
BidiAudioChunk is the audio carried by one realtimeInput frame. Both the current `audio` field and the older `mediaChunks` array are accepted: the vendor's own SDKs still emit the latter, and refusing it would make working client code fail at the Router for no transport reason.
type BidiSetup ¶
type BidiSetup struct {
Setup BidiSetupConfig `json:"setup"`
}
BidiSetup is the first text frame of a GET /v1/bidi session: the vendor's own setup message. Unknown fields are refused so the Router forwards exactly what it validated.
func DecodeBidiSetup ¶
DecodeBidiSetup decodes the first frame strictly: unknown fields anywhere in the message are refused, so a caller learns that the Router dropped nothing rather than discovering it at the vendor.
type BidiSetupConfig ¶
type BidiSetupConfig struct {
// Model is the exact Gemini Live model id. The vendor spells it
// "models/<id>"; both spellings are accepted and ModelID normalizes.
Model string `json:"model"`
// GenerationConfig carries everything the vendor files under it on the
// wire: responseModalities, speechConfig, thinkingConfig (Gemini 3.8's
// thinkingLevel / includeThoughts), enableAffectiveDialog,
// mediaResolution, translationConfig and the sampling scalars. The SDK's
// flat LiveConnectConfig fields (thinking_config, enable_affective_dialog,
// media_resolution, temperature, …) all land HERE, which is why none of
// them is a top-level setup member. Kept verbatim within its bound
// because the shape belongs to the vendor.
GenerationConfig json.RawMessage `json:"generationConfig,omitempty"`
// SystemInstruction steers the live model.
SystemInstruction json.RawMessage `json:"systemInstruction,omitempty"`
// Tools are forwarded verbatim; function calls come back as toolCall
// server messages and are answered with a toolResponse client message.
Tools []json.RawMessage `json:"tools,omitempty"`
// SessionResumption and ContextWindowCompression are vendor session
// settings the Router passes through unchanged.
SessionResumption json.RawMessage `json:"sessionResumption,omitempty"`
ContextWindowCompression json.RawMessage `json:"contextWindowCompression,omitempty"`
// InputAudioTranscription and OutputAudioTranscription enable the
// vendor's own transcripts; both ride through untouched.
InputAudioTranscription json.RawMessage `json:"inputAudioTranscription,omitempty"`
OutputAudioTranscription json.RawMessage `json:"outputAudioTranscription,omitempty"`
// RealtimeInputConfig tunes vendor-side VAD and turn handling.
RealtimeInputConfig json.RawMessage `json:"realtimeInputConfig,omitempty"`
// Proactivity (proactiveAudio) and HistoryConfig
// (initialHistoryInClientContent) complete the setup members the vendor's
// Live reference documents; both ride through untouched.
Proactivity json.RawMessage `json:"proactivity,omitempty"`
HistoryConfig json.RawMessage `json:"historyConfig,omitempty"`
// SafetySettings and Labels are absent from the Live reference page but
// present on the vendor's v1beta wire schema for this setup message, and
// the vendor's own SDK emits both to this endpoint
// (LiveConnectConfig.safety_settings / labels). Because unknown fields are
// refused, leaving them out would break any client that set either.
SafetySettings json.RawMessage `json:"safetySettings,omitempty"`
Labels json.RawMessage `json:"labels,omitempty"`
}
BidiSetupConfig is the setup object.
func (BidiSetupConfig) ModelID ¶
func (c BidiSetupConfig) ModelID() string
ModelID is the bare catalog model id, with the vendor's "models/" prefix removed. The catalog and the signed plan both speak the bare id; accepting either spelling keeps a copy-pasted vendor snippet working.
func (BidiSetupConfig) Validate ¶
func (c BidiSetupConfig) Validate() error
Validate checks the setup object.
type ContentHasher ¶
type ContentHasher struct {
// contains filtered or unexported fields
}
ContentHasher computes the canonical content hash incrementally. It exists for multipart bodies, whose parts are streamed into the hash in order without buffering the audio; hashing one complete buffer through it matches HashContent exactly.
func NewContentHasher ¶
func NewContentHasher() *ContentHasher
NewContentHasher returns a hasher ready for the first byte.
func (*ContentHasher) Sum ¶
func (c *ContentHasher) Sum() string
Sum returns the canonical content hash of everything written so far.
type ContentPart ¶
ContentPart is one piece of a message's content.
type ErrorBody ¶
type ErrorBody struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Hint string `json:"hint"`
Retryable bool `json:"retryable"`
RequestID string `json:"request_id,omitempty"`
}
ErrorBody is the normalized failure detail. Message is human-readable and intentionally carries no provider payload; RequestID is present whenever a relay request id had been minted before the failure.
type ErrorCode ¶
type ErrorCode string
ErrorCode is a stable, machine-readable failure class. The set is closed: the relay normalizes every failure — including provider failures — to one of these codes and never forwards a raw provider response body.
When an error envelope travels as an HTTP response, each code maps to one canonical status — retry logic commonly keys off the status before parsing the body, so the mapping is contract, not implementation detail:
400 capability_unsupported, invalid_request 401 authentication_failed 402 insufficient_credit 404 route_not_found 405 method_not_allowed 409 idempotency_conflict, request_in_progress, request_already_started 413 payload_too_large 415 unsupported_media 429 rate_limited, concurrency_exhausted 500 relay_error 502 provider_error 503 provider_unavailable 504 request_timeout
budget_exhausted and lease_expired terminate streams that are already established — an SSE error event or a WebSocket error frame after the 200 or the upgrade — so no HTTP status carries them.
const ( ErrorCodeAuthenticationFailed ErrorCode = "authentication_failed" ErrorCodeInsufficientCredit ErrorCode = "insufficient_credit" ErrorCodeCapabilityUnsupported ErrorCode = "capability_unsupported" ErrorCodeInvalidRequest ErrorCode = "invalid_request" ErrorCodeRouteNotFound ErrorCode = "route_not_found" ErrorCodeMethodNotAllowed ErrorCode = "method_not_allowed" ErrorCodeRateLimited ErrorCode = "rate_limited" ErrorCodeConcurrencyExhausted ErrorCode = "concurrency_exhausted" ErrorCodeProviderError ErrorCode = "provider_error" ErrorCodeRelayError ErrorCode = "relay_error" // ErrorCodeIdempotencyConflict reports an Idempotency-Key reused with a // different content hash. The other two idempotency codes report a reuse // with the SAME hash: request_in_progress while a prior admission is // still live (retryable), request_already_started once output may have // been produced — stateless mode cannot replay output, so the caller // gets the original request id instead of a rerun. ErrorCodeIdempotencyConflict ErrorCode = "idempotency_conflict" ErrorCodeRequestInProgress ErrorCode = "request_in_progress" ErrorCodeRequestAlreadyStarted ErrorCode = "request_already_started" ErrorCodeBudgetExhausted ErrorCode = "budget_exhausted" ErrorCodeLeaseExpired ErrorCode = "lease_expired" ErrorCodePayloadTooLarge ErrorCode = "payload_too_large" ErrorCodeUnsupportedMedia ErrorCode = "unsupported_media" ErrorCodeRequestTimeout ErrorCode = "request_timeout" )
func ErrorCodes ¶
func ErrorCodes() []ErrorCode
ErrorCodes returns the closed code set in a stable order. It exists so spec drift checks and exhaustive tests never re-list the codes by hand.
type ErrorEnvelope ¶
type ErrorEnvelope struct {
Error ErrorBody `json:"error"`
}
ErrorEnvelope is the body of every non-2xx HTTP response and the data payload of the SSE error event, so both transports share one normalized error shape.
func (ErrorEnvelope) Event ¶
func (ErrorEnvelope) Event() string
Event returns the SSE event name for the failure terminal event. The HTTP error envelope doubles as the SSE error payload so both transports share one normalized error shape.
func (ErrorEnvelope) Validate ¶
func (e ErrorEnvelope) Validate() error
Validate checks the enclosed body.
type ErrorEvent ¶
ErrorEvent is the terminal error frame on a WebSocket session. Exactly one terminal frame — session.closed or error — ends every session.
func (ErrorEvent) Validate ¶
func (e ErrorEvent) Validate() error
Validate checks the frame tag and the enclosed body.
type EvaluationAnswer ¶
type EvaluationAnswer struct {
Type string `json:"type"`
Noul *float64 `json:"noul,omitempty"`
Choice string `json:"choice,omitempty"`
Score *float64 `json:"score,omitempty"`
Probabilities map[string]float64 `json:"probabilities,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
Legend map[string]json.RawMessage `json:"legend,omitempty"`
}
type EvaluationLimits ¶ added in v0.3.1
type EvaluationLimits struct {
MaxQuestions int `json:"max_questions,omitempty"`
MaxChoiceOptions int `json:"max_choice_options,omitempty"`
MaxScoreLevels int `json:"max_score_levels,omitempty"`
MaxInstructionChars int `json:"max_instruction_chars,omitempty"`
MaxContextChars int `json:"max_context_chars,omitempty"`
MaxOptionNameChars int `json:"max_option_name_chars,omitempty"`
MaxOptionDescriptionChars int `json:"max_option_description_chars,omitempty"`
MaxScoreLevelChars int `json:"max_score_level_chars,omitempty"`
MaxNoulCriterionChars int `json:"max_noul_criterion_chars,omitempty"`
MinAudioMS int64 `json:"min_audio_ms,omitempty"`
MaxAudioMS int64 `json:"max_audio_ms,omitempty"`
MaxAudioBytes int64 `json:"max_audio_bytes,omitempty"`
}
EvaluationLimits are one model's published bounds on an evaluation request. A zero field means the model publishes no such bound. Callers that want to switch models freely validate against the intersection of the models they use; the relay refuses a request the routed model's limits do not accept with capability_unsupported before admission.
func (EvaluationLimits) Accepts ¶ added in v0.3.1
func (l EvaluationLimits) Accepts(shape EvaluationShape) (string, bool)
Accepts reports whether the limits admit the shape, naming the first limit it exceeds (or "min_audio_ms" for a clip that is too short).
func (EvaluationLimits) Validate ¶ added in v0.3.1
func (l EvaluationLimits) Validate() error
Validate checks that the limits are internally consistent.
type EvaluationQuestion ¶
type EvaluationQuestion struct {
Type string `json:"type"`
Instructions json.RawMessage `json:"instructions"`
Criteria json.RawMessage `json:"criteria,omitempty"`
}
func (*EvaluationQuestion) UnmarshalJSON ¶
func (q *EvaluationQuestion) UnmarshalJSON(data []byte) error
func (EvaluationQuestion) Validate ¶
func (q EvaluationQuestion) Validate() error
type EvaluationRequest ¶
type EvaluationRequest struct {
Routing Routing `json:"routing"`
State json.RawMessage `json:"state"`
Questions map[string]EvaluationQuestion `json:"questions"`
}
EvaluationRequest preserves TypeSafe's native state/questions shape and adds only Speko's explicit route selector.
func (EvaluationRequest) HasState ¶ added in v0.3.1
func (r EvaluationRequest) HasState() bool
HasState reports whether the request carries state. Absent and JSON null are the same: EvaluationRequest always marshals the field, so a request built without state round-trips as "state":null.
func (EvaluationRequest) Shape ¶ added in v0.3.1
func (r EvaluationRequest) Shape() EvaluationShape
Shape measures the request's questions and context. Call it on a request that already passed Validate or ValidateAudio.
func (*EvaluationRequest) UnmarshalJSON ¶
func (r *EvaluationRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON keeps the evaluation surface closed. Generation-only fields such as stream, temperature, tools, and max_output_tokens are therefore rejected instead of being silently ignored by encoding/json.
func (EvaluationRequest) Validate ¶
func (r EvaluationRequest) Validate() error
func (EvaluationRequest) ValidateAudio ¶ added in v0.3.1
func (r EvaluationRequest) ValidateAudio() error
ValidateAudio checks the request part of an audio evaluation. It is Validate with the two rules every audio decision vendor shares:
- state is optional and, when present, is plain-text context about the clip (who is speaking, what was said before). It is never the decided material; the audio is.
- instructions, option descriptions, noul criteria and score levels are plain text. Structured JSON content is a text-evaluation feature.
Question ids must match [A-Za-z0-9_-]{1,64}. Per-model bounds (question count, option count, text lengths, audio duration) are advertised in ModelCapabilities.EvaluationLimits and checked against the routed model.
type EvaluationResponse ¶
type EvaluationResponse struct {
Model string `json:"model"`
Answers map[string]EvaluationAnswer `json:"answers"`
Usage Usage `json:"usage"`
}
func (EvaluationResponse) ValidateFor ¶
func (r EvaluationResponse) ValidateFor(request EvaluationRequest) error
ValidateFor proves that an upstream response answers exactly the questions sent and cannot introduce an option or score level absent from the request.
type EvaluationShape ¶ added in v0.3.1
type EvaluationShape struct {
Questions int
MaxChoiceOptions int
MaxScoreLevels int
MaxInstructionChars int
ContextChars int
MaxOptionNameChars int
MaxOptionDescriptionChars int
MaxScoreLevelChars int
MaxNoulCriterionChars int
// Audio is true when the request carries a clip. Audio bounds apply only
// then, so a model that takes both text and audio does not hold text
// requests to its minimum clip duration.
Audio bool
AudioMS int64
AudioBytes int64
}
EvaluationShape measures a request in the units EvaluationLimits bound. Character counts are Unicode code points of the text values; the audio fields are filled in by whoever parsed the clip.
type FunctionTool ¶
type FunctionTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
}
FunctionTool declares a caller-defined function the model may call. Parameters is the function's JSON Schema; the relay passes it through and enforces only that it is well-formed JSON — schema semantics belong to the provider. Tools are admitted only on models advertising the capability.
func (FunctionTool) Validate ¶
func (t FunctionTool) Validate() error
Validate checks the tool declaration.
type Item ¶
type Item struct {
Type ItemType `json:"type"`
// Message fields.
Role MessageRole `json:"role,omitempty"`
Content []ContentPart `json:"content,omitempty"`
// Function call fields (CallID is shared with function_result: it links
// a result to the call that produced it).
CallID string `json:"call_id,omitempty"`
Name string `json:"name,omitempty"`
Arguments string `json:"arguments,omitempty"`
// Function result field.
Result string `json:"result,omitempty"`
// Structured output field.
JSON json.RawMessage `json:"json,omitempty"`
}
Item is the tagged union entry of LLM input and output. Callers resend full conversation history on every request — including function_call and function_result items — because the relay stores no conversation state and exposes no previous_response_id.
Arguments is JSON carried as a string, matching how function call arguments stream as text deltas. Result is opaque text: the relay passes it through without requiring JSON, and it may legitimately be empty — a function can succeed and have nothing to say. JSON is a raw structured value.
func (Item) Validate ¶
Validate checks a complete item: the variant's own rules plus the union discipline that no other variant's fields are set. Streaming uses a relaxed shell check at response.item.added time — see llm_stream.go — because deltas have not yet delivered arguments or structured JSON.
type ItemType ¶
type ItemType string
ItemType tags every entry of an LLM request input or response output. The union is closed and flat: exactly one variant's fields may be set, and fields from another variant are rejected rather than ignored.
const ( ItemTypeMessage ItemType = "message" ItemTypeFunctionCall ItemType = "function_call" ItemTypeFunctionResult ItemType = "function_result" // ItemTypeStructuredJSON carries the model's schema-conforming JSON when // the request asked for structured output. It is output-only: // LLMRequest.Validate rejects it in input, because resent history // represents earlier structured output as ordinary assistant text. ItemTypeStructuredJSON ItemType = "structured_json" )
type Kind ¶
type Kind string
Kind selects the provider-neutral operation served by the relay: stt, tts, llm, and s2s. Speech-to-speech rows are served on protocol-specific public routes (Model.Endpoint) speaking the vendor's native event protocol (Model.Protocol) rather than a Router-neutral envelope.
type LLMRequest ¶
type LLMRequest struct {
Routing Routing `json:"routing"`
Input []Item `json:"input"`
Tools []FunctionTool `json:"tools,omitempty"`
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
MaxOutputTokens int64 `json:"max_output_tokens"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
Stream bool `json:"stream,omitempty"`
}
LLMRequest is the POST /v1/llm/responses body. MaxOutputTokens is required: the relay reserves credit for the worst-case generation before dispatch, and an unbounded generation cannot be priced.
func (LLMRequest) Validate ¶
func (r LLMRequest) Validate() error
Validate checks the full request contract. Callers normalize Routing with NormalizeDefault first — an omitted routing object defaults to {mode: auto, objective: balanced}.
type LLMResponse ¶
type LLMResponse struct {
ID string `json:"id"`
Route Route `json:"route"`
Output []Item `json:"output"`
StopReason StopReason `json:"stop_reason"`
Usage Usage `json:"usage"`
}
LLMResponse is the non-streaming POST /v1/llm/responses body. There is no previous_response_id to feed it back into: callers resend full history.
func (LLMResponse) Validate ¶
func (r LLMResponse) Validate() error
Validate checks the full response contract, including that the id carries the Speko-minted prefix.
type LiveAudioConfig ¶
type LiveAudioConfig struct {
Format *LiveAudioFormat `json:"format,omitempty"`
Output *LiveAudioOutput `json:"output,omitempty"`
}
LiveAudioConfig is session.audio.
func (LiveAudioConfig) Validate ¶
func (a LiveAudioConfig) Validate() error
Validate checks the audio block: PCM16 at a transported rate.
type LiveAudioFormat ¶
LiveAudioFormat is the shared input/output audio format.
func (LiveAudioFormat) Validate ¶
func (f LiveAudioFormat) Validate() error
Validate refuses every format but mono PCM16 at a transported rate.
type LiveAudioOutput ¶
type LiveAudioOutput struct {
Voice string `json:"voice,omitempty"`
}
LiveAudioOutput is session.audio.output.
type LiveContentPart ¶
LiveContentPart is one text part of a seeded message.
type LiveDelegationConfig ¶
type LiveDelegationConfig struct {
Type string `json:"type"`
Responses *LiveResponsesConfig `json:"responses,omitempty"`
}
LiveDelegationConfig is session.delegation.
func (LiveDelegationConfig) Validate ¶
func (d LiveDelegationConfig) Validate() error
Validate checks the delegation block. Responses delegation requires an explicit backend model.
type LiveInputItem ¶
type LiveInputItem struct {
Type string `json:"type,omitempty"`
Role string `json:"role"`
Content []LiveContentPart `json:"content"`
}
LiveInputItem is one seeded history message.
func (LiveInputItem) Validate ¶
func (i LiveInputItem) Validate() error
Validate checks one seeded message.
type LiveResponsesConfig ¶
type LiveResponsesConfig struct {
Model string `json:"model"`
Instructions string `json:"instructions,omitempty"`
Tools []json.RawMessage `json:"tools,omitempty"`
ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`
MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
ServiceTier string `json:"service_tier,omitempty"`
Reasoning json.RawMessage `json:"reasoning,omitempty"`
Text json.RawMessage `json:"text,omitempty"`
}
LiveResponsesConfig is session.delegation.responses: the Responses backend GPT-Live delegates to. Tools, tool_choice, reasoning, and text are kept verbatim within their size bounds because their shapes belong to the backend model.
func (LiveResponsesConfig) ToolTypes ¶
func (c LiveResponsesConfig) ToolTypes() []string
ToolTypes returns the distinct declared tool types in declaration order.
func (LiveResponsesConfig) Validate ¶
func (c LiveResponsesConfig) Validate() error
Validate checks the backend configuration.
type LiveSessionConfig ¶
type LiveSessionConfig struct {
// Model is the exact GPT-Live model id; auto selection is not offered on
// this route.
Model string `json:"model"`
// Instructions steer the live voice model. Backend instructions live on
// delegation.responses.instructions and are never merged into these.
Instructions string `json:"instructions,omitempty"`
// Audio declares the one PCM16 format used in both directions and the
// output voice (default marin).
Audio *LiveAudioConfig `json:"audio,omitempty"`
// Input seeds prior text messages.
Input []LiveInputItem `json:"input,omitempty"`
// Delegation selects client or responses delegation; omitted or null is
// client delegation.
Delegation *LiveDelegationConfig `json:"delegation,omitempty"`
// Store must be false or omitted: the Router never persists session
// recordings at the vendor on a caller's behalf.
Store *bool `json:"store,omitempty"`
}
LiveSessionConfig is the session object of session.start.
func (LiveSessionConfig) DelegationType ¶
func (c LiveSessionConfig) DelegationType() string
DelegationType returns the effective delegation mode.
func (LiveSessionConfig) SampleRateHz ¶
func (c LiveSessionConfig) SampleRateHz() int
SampleRateHz returns the declared PCM rate, defaulting to 24 kHz.
func (LiveSessionConfig) Validate ¶
func (c LiveSessionConfig) Validate() error
Validate checks the session object.
func (LiveSessionConfig) Voice ¶
func (c LiveSessionConfig) Voice() string
Voice returns the requested output voice, "" when the caller left it to the route default.
type LiveSessionStart ¶
type LiveSessionStart struct {
Type string `json:"type"`
EventID string `json:"event_id,omitempty"`
Session LiveSessionConfig `json:"session"`
}
LiveSessionStart is the first text frame of a GET /v1/live session: the native GPT-Live session.start command. Unknown session fields are refused so the Router forwards exactly what it validated.
func DecodeLiveSessionStart ¶
func DecodeLiveSessionStart(raw []byte) (LiveSessionStart, error)
DecodeLiveSessionStart decodes the first frame strictly: unknown fields anywhere in the command are refused, so a caller learns that the Router dropped nothing rather than discovering it at the vendor.
func (LiveSessionStart) Validate ¶
func (s LiveSessionStart) Validate() error
Validate checks the session.start command.
type MessageRole ¶
type MessageRole string
MessageRole is the closed author set for message items. There is no tool role: tool traffic uses the dedicated function_call and function_result item types.
const ( RoleSystem MessageRole = "system" RoleUser MessageRole = "user" RoleAssistant MessageRole = "assistant" )
type Model ¶
type Model struct {
ID string `json:"id"`
Provider string `json:"provider"`
Kind Kind `json:"kind"`
Capabilities ModelCapabilities `json:"capabilities"`
Regions []string `json:"regions"`
// AudioFormats lists accepted input formats for STT and S2S models and
// output formats for TTS models.
AudioFormats []AudioFormat `json:"audio_formats,omitempty"`
// OutputAudioFormats lists the formats an S2S model speaks in; omitted
// for every other kind.
OutputAudioFormats []AudioFormat `json:"output_audio_formats,omitempty"`
BatchAudioLimits *BatchAudioLimits `json:"batch_audio_limits,omitempty"`
// Endpoint is the public Router route an S2S model is served on
// (/v1/realtime, /v1/live, /v1/bidi, /v1/realtime/translations, or
// /v1/realtime/translations/qwen); multiple native protocols may share a
// route and are disambiguated by the exact model id. Omitted for every other kind,
// whose routes are fixed per kind.
Endpoint string `json:"endpoint,omitempty"`
// Protocol names the native event protocol an S2S route speaks
// (openai.realtime.v1, xai.realtime.v1, openai.live.v1, google.live.v1,
// openai.realtime.translation.v1, alibaba.livetranslate.v1); omitted for
// every other kind. It also tells a client how to FRAME its messages:
// OpenAI, xAI, GPT-Live and both translation protocols tag by "type";
// google.live.v1 uses a top-level key.
Protocol string `json:"protocol,omitempty"`
Benchmark *ModelBenchmark `json:"benchmark,omitempty"`
}
Model is one currently routable catalog entry. Regions lists the Speko Router regions (AWS region ids) where the model is routable right now — relay locations, never provider-processing residency.
type ModelBenchmark ¶
type ModelBenchmark struct {
Rank int `json:"rank,omitempty"`
Provider string `json:"provider"`
Model string `json:"model"`
Quality *float64 `json:"quality,omitempty"`
QualityAxis string `json:"quality_axis,omitempty"`
LowerIsBetter bool `json:"quality_lower_is_better"`
QualityPath string `json:"quality_path,omitempty"`
LanguageCode string `json:"language_code,omitempty"`
CarriedFrom string `json:"carried_from,omitempty"`
LatencyMS *float64 `json:"latency_ms,omitempty"`
FirstPartialMS *float64 `json:"first_partial_ms,omitempty"`
Cost json.RawMessage `json:"cost,omitempty"`
CostBasis string `json:"cost_basis,omitempty"`
Drift *float64 `json:"drift,omitempty"`
BalancedScore *float64 `json:"balanced_score,omitempty"`
Language json.RawMessage `json:"language,omitempty"`
}
ModelBenchmark annotates one exact route with the measurement used for the requested model-list projection. Cost and Language retain the source JSON so evidence fields can grow compatibly without flattening the benchmark schema into the serving contract.
type ModelCapabilities ¶
type ModelCapabilities struct {
// Streaming says the model supports its kind's public streaming operation:
// live audio processing for STT, incremental text/audio sessions for TTS,
// streamed output for LLM, and bidirectional realtime audio for S2S.
Streaming bool `json:"streaming"`
Tools bool `json:"tools"`
StructuredOutput bool `json:"structured_output"`
CachedInput bool `json:"cached_input"`
Reasoning bool `json:"reasoning"`
Diarization bool `json:"diarization"`
// LanguageIdentification is support for opt-in language labels on
// streaming STT segments, independent of the model's batch support.
LanguageIdentification bool `json:"language_identification,omitempty"`
Keywords bool `json:"keywords"`
NoiseReduction bool `json:"noise_reduction"`
// WordTimestamps says whether an STT model can be ASKED for per-word
// start/end timings on the batch transcription result
// (STTOptions.WordTimestamps → TranscriptionResponse.Words). Distinct
// from WordTimings, which describes what a TTS route emits unasked.
WordTimestamps bool `json:"word_timestamps"`
// WordTimings and CharacterTimings say whether a TTS model reports
// time-aligned speech spans, and at which granularity it MEASURES them.
// They are separate bits rather than one enum because a model may report
// both, and neither is derived from the other: the relay never groups
// characters into words on the caller's behalf.
WordTimings bool `json:"word_timings"`
CharacterTimings bool `json:"character_timings"`
// Translation says the model translates: speech in, speech in another
// language out (S2S), or speech in, translated text out (STT). A model
// with this bit set is a translation model, not a conversational one:
// its route carries a target language and returns no assistant turn.
Translation bool `json:"translation"`
EvaluationQuestionTypes []string `json:"evaluation_question_types,omitempty"`
// EvaluationInputs lists what an evaluation model decides over: "text"
// (a JSON body with state) and/or "audio" (a multipart body with a WAV
// clip). Omitted means text only. Evaluation models only.
EvaluationInputs []string `json:"evaluation_inputs,omitempty"`
// EvaluationLimits are the model's published request bounds. Omitted or
// zero fields mean no published bound. Evaluation models only.
EvaluationLimits *EvaluationLimits `json:"evaluation_limits,omitempty"`
}
ModelCapabilities advertises what a model supports. Capability gating happens before admission: a request using a capability a model does not advertise is rejected with capability_unsupported, never silently stripped.
func (ModelCapabilities) AcceptsEvaluationInput ¶ added in v0.3.1
func (c ModelCapabilities) AcceptsEvaluationInput(input string) bool
AcceptsEvaluationInput reports whether an evaluation model takes the input ("text" or "audio"). No advertised inputs means text only.
func (ModelCapabilities) SupportsSTTOptions ¶
func (c ModelCapabilities) SupportsSTTOptions(options *STTOptions) (string, bool)
SupportsSTTOptions reports whether this model advertises every canonical ask the options carry, and names the first one it does not. Provider settings are the routed vendor's own and are not checked here.
type ModelsResponse ¶
type ModelsResponse struct {
Models []Model `json:"models"`
CatalogDigest string `json:"catalog_digest"`
Benchmark BenchmarkMetadata `json:"benchmark"`
}
ModelsResponse is the GET /v1/models body: the currently routable slice of the catalog. CatalogDigest identifies the release-pinned catalog that produced the listing so support can correlate a caller's view with an exact release.
func (ModelsResponse) Validate ¶
func (m ModelsResponse) Validate() error
Validate checks every entry and the catalog digest format.
type ResponseCompleted ¶
type ResponseCompleted struct {
StopReason StopReason `json:"stop_reason"`
Usage Usage `json:"usage"`
}
ResponseCompleted is the success terminal event, carrying the stop reason and the authoritative usage for the whole response.
func (ResponseCompleted) Event ¶
func (ResponseCompleted) Event() string
Event returns the SSE event name.
func (ResponseCompleted) Validate ¶
func (e ResponseCompleted) Validate() error
Validate checks the stop reason and usage.
type ResponseCreated ¶
type ResponseCreated struct {
ResponseID string `json:"response_id"`
}
ResponseCreated opens every stream. ResponseID is Speko-minted — ResponseID(request_id), never a provider identifier — and matches the ID a non-streaming call would have returned.
func (ResponseCreated) Event ¶
func (ResponseCreated) Event() string
Event returns the SSE event name.
func (ResponseCreated) Validate ¶
func (e ResponseCreated) Validate() error
Validate checks that the id carries the Speko-minted prefix.
type ResponseFormat ¶
type ResponseFormat struct {
Type string `json:"type"`
Name string `json:"name"`
Schema json.RawMessage `json:"schema"`
Strict bool `json:"strict,omitempty"`
}
ResponseFormat requests schema-conforming structured output. It is admitted only on models advertising structured output support.
func (ResponseFormat) Validate ¶
func (f ResponseFormat) Validate() error
Validate checks the format declaration.
type ResponseFunctionCallArgumentsDelta ¶
type ResponseFunctionCallArgumentsDelta struct {
OutputIndex int `json:"output_index"`
Delta string `json:"delta"`
}
ResponseFunctionCallArgumentsDelta appends argument text to the function_call item at OutputIndex. The concatenated deltas form the JSON arguments finalized in response.item.completed.
func (ResponseFunctionCallArgumentsDelta) Event ¶
func (ResponseFunctionCallArgumentsDelta) Event() string
Event returns the SSE event name.
func (ResponseFunctionCallArgumentsDelta) Validate ¶
func (e ResponseFunctionCallArgumentsDelta) Validate() error
Validate checks the index and that the delta says something — empty provider deltas are dropped at normalization, never forwarded.
type ResponseItemAdded ¶
ResponseItemAdded announces a new output item at OutputIndex. The item is a shell: its streamed content (message text, function call arguments, structured JSON) arrives through subsequent delta events and is complete only in response.item.completed.
func (ResponseItemAdded) Event ¶
func (ResponseItemAdded) Event() string
Event returns the SSE event name.
func (ResponseItemAdded) Validate ¶
func (e ResponseItemAdded) Validate() error
Validate checks the index and the item shell. The shell check relaxes only the not-yet-streamed content; identity fields must be final, and the shell obeys the output-side union narrowing — no function_result shells, no non-assistant messages.
type ResponseItemCompleted ¶
ResponseItemCompleted carries the finalized item at OutputIndex — the same value a non-streaming response would contain at that position.
func (ResponseItemCompleted) Event ¶
func (ResponseItemCompleted) Event() string
Event returns the SSE event name.
func (ResponseItemCompleted) Validate ¶
func (e ResponseItemCompleted) Validate() error
Validate checks the index and the complete item under the output-side union narrowing — the same rules a non-streaming response's output obeys.
type ResponseTextDelta ¶
ResponseTextDelta appends text to the message or structured_json item at OutputIndex.
func (ResponseTextDelta) Event ¶
func (ResponseTextDelta) Event() string
Event returns the SSE event name.
func (ResponseTextDelta) Validate ¶
func (e ResponseTextDelta) Validate() error
Validate checks the index and that the delta says something — empty provider deltas are dropped at normalization, never forwarded.
type Route ¶
type Route struct {
Provider string `json:"provider"`
Model string `json:"model"`
Region string `json:"region"`
AttemptID string `json:"attempt_id"`
}
Route is the response-side counterpart of Routing: the concrete decision that served a request. Region is the Speko Router location, not a provider-processing residency guarantee, and AttemptID identifies the (possibly post-fallback) attempt that produced the output.
type Routing ¶
type Routing struct {
Mode RoutingMode `json:"mode,omitempty"`
Objective RoutingObjective `json:"objective,omitempty"`
AllowProviders []string `json:"allow_providers,omitempty"`
DenyProviders []string `json:"deny_providers,omitempty"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
}
Routing selects how the relay picks a provider for one request. It is a tagged union over Mode: auto carries the objective and optional allow/deny provider filters, explicit carries exactly a provider and model. Fields from the other arm are rejected in both directions — with one documented asymmetry in what "present" means. JSON distinguishes a present-but-empty array from an omitted one, so an explicit routing carrying allow_providers or deny_providers as [] is rejected like any other cross-arm field. The string fields cannot make that distinction without pointer types, so "provider": "" in auto mode is indistinguishable from omission and tolerated as such.
A wholly omitted routing object means {mode: auto, objective: balanced}. Handlers apply that default with NormalizeDefault before Validate; Validate deliberately rejects the unnormalized zero forms so no code path can skip the defaulting decision silently.
func (Routing) NormalizeDefault ¶
NormalizeDefault returns the routing with the contract defaults applied: a zero routing (the caller omitted the object entirely) becomes {mode: auto, objective: balanced}, and an auto routing without an objective defaults to balanced. A routing that names any other field without a mode is returned unchanged so Validate rejects it — the default exists for omission, never for partially specified routing. An empty filter array counts as naming the field: {"allow_providers": []} is a partially specified routing, not an omitted one.
Explicit mode additionally accepts the combined "provider/model" spelling in the model field: {"model": "openai/gpt-5.2"} with no provider splits at the FIRST slash into provider "openai" and model "gpt-5.2", and a model redundantly prefixed with the provider field's own value ("provider": "openai", "model": "openai/gpt-5.2") has the prefix stripped. Splitting at the first slash is what keeps slash-bearing upstream ids expressible: "together/meta-llama/Llama-X" names provider "together" and model "meta-llama/Llama-X". A model whose own id contains a slash therefore cannot be sent without naming its provider one way or the other — the leading segment is always claimed as the provider — which is the existing contract anyway: explicit mode has never accepted a bare model.
type RoutingMode ¶
type RoutingMode string
RoutingMode discriminates the routing tagged union. The set is closed: an empty or unknown mode is rejected so a typo can never silently fall back to automatic provider selection.
const ( RoutingModeAuto RoutingMode = "auto" RoutingModeExplicit RoutingMode = "explicit" )
type RoutingObjective ¶
type RoutingObjective string
RoutingObjective ranks auto-mode candidates. Unknown objectives are rejected rather than treated as balanced so callers learn about typos before any money is reserved.
const ( ObjectiveBalanced RoutingObjective = "balanced" ObjectiveQuality RoutingObjective = "quality" ObjectiveLatency RoutingObjective = "latency" ObjectiveCost RoutingObjective = "cost" )
type S2SAudioConfig ¶
type S2SAudioConfig struct {
Input AudioConfig `json:"input"`
Output AudioConfig `json:"output"`
}
S2SAudioConfig declares both directions of a speech-to-speech session: the raw binary frames the client sends and the raw binary frames it wants back. Streamed audio has no container, so both formats are declared up front, and they may differ — most models listen and speak at different rates.
func (S2SAudioConfig) Validate ¶
func (a S2SAudioConfig) Validate() error
Validate checks both directions.
type S2SControlType ¶
type S2SControlType string
S2SControlType is retained for decoding legacy internal connector frames. The Relay exposes no public speech-to-speech media route.
const ( // S2SControlSessionConfigure must be the first text frame on the socket. // Its exact frame bytes are the WebSocket idempotency content hash (see // idempotency.go); later frames are intentionally outside the hash. S2SControlSessionConfigure S2SControlType = "session.configure" // S2SControlInputCommit tells the model the caller finished speaking. It // is a hint: every routed model also detects turn ends on its own. S2SControlInputCommit S2SControlType = "input.commit" // S2SControlResponseCancel interrupts the answer the model is speaking // (barge-in). Audio already delivered stays delivered and billed. S2SControlResponseCancel S2SControlType = "response.cancel" S2SControlSessionClose S2SControlType = "session.close" )
type S2SEventType ¶
type S2SEventType string
S2SEventType is retained for decoding legacy internal connector frames.
const ( S2SEventSessionReady S2SEventType = "session.ready" S2SEventInputSpeechStarted S2SEventType = "input.speech_started" S2SEventInputSpeechEnded S2SEventType = "input.speech_ended" S2SEventInputTranscript S2SEventType = "input.transcript" S2SEventResponseStarted S2SEventType = "response.started" S2SEventResponseTranscriptDelta S2SEventType = "response.transcript.delta" S2SEventResponseDone S2SEventType = "response.done" S2SEventResponseCancelled S2SEventType = "response.cancelled" S2SEventUsageUpdated S2SEventType = "usage.updated" S2SEventSessionClosed S2SEventType = "session.closed" S2SEventError S2SEventType = "error" )
type S2SInputCommit ¶
type S2SInputCommit struct {
Type S2SControlType `json:"type"`
}
S2SInputCommit tells the model the caller finished speaking.
func (S2SInputCommit) Validate ¶
func (c S2SInputCommit) Validate() error
Validate checks the frame tag.
type S2SInputSpeechEnded ¶
type S2SInputSpeechEnded struct {
Type S2SEventType `json:"type"`
}
S2SInputSpeechEnded reports that the model detected the caller's turn end.
func (S2SInputSpeechEnded) Validate ¶
func (e S2SInputSpeechEnded) Validate() error
Validate checks the frame tag.
type S2SInputSpeechStarted ¶
type S2SInputSpeechStarted struct {
Type S2SEventType `json:"type"`
}
S2SInputSpeechStarted reports that the model detected the caller speaking.
func (S2SInputSpeechStarted) Validate ¶
func (e S2SInputSpeechStarted) Validate() error
Validate checks the frame tag.
type S2SInputTranscript ¶
type S2SInputTranscript struct {
Type S2SEventType `json:"type"`
Text string `json:"text"`
Final bool `json:"final"`
}
S2SInputTranscript is the model's transcription of what the caller said. Final marks a completed span; a non-final transcript is an interim hypothesis superseded by later frames.
func (S2SInputTranscript) Validate ¶
func (e S2SInputTranscript) Validate() error
Validate checks the frame tag. Text may be empty on a final frame: a finalized span of silence is legitimate.
type S2SResponseCancel ¶
type S2SResponseCancel struct {
Type S2SControlType `json:"type"`
}
S2SResponseCancel interrupts the answer being spoken.
func (S2SResponseCancel) Validate ¶
func (c S2SResponseCancel) Validate() error
Validate checks the frame tag.
type S2SResponseCancelled ¶
type S2SResponseCancelled struct {
Type S2SEventType `json:"type"`
Sequence int `json:"sequence"`
}
S2SResponseCancelled reports that an answer stopped before it finished — because the caller interrupted it (barge-in or response.cancel). No response.done follows for that sequence.
func (S2SResponseCancelled) Validate ¶
func (e S2SResponseCancelled) Validate() error
Validate checks the frame tag and sequence.
type S2SResponseDone ¶
type S2SResponseDone struct {
Type S2SEventType `json:"type"`
Sequence int `json:"sequence"`
}
S2SResponseDone marks the end of one answer's binary audio frames.
func (S2SResponseDone) Validate ¶
func (e S2SResponseDone) Validate() error
Validate checks the frame tag and sequence.
type S2SResponseStarted ¶
type S2SResponseStarted struct {
Type S2SEventType `json:"type"`
Sequence int `json:"sequence"`
}
S2SResponseStarted announces the binary audio frames of one spoken answer. Sequence is the 1-based answer index within the session.
func (S2SResponseStarted) Validate ¶
func (e S2SResponseStarted) Validate() error
Validate checks the frame tag and sequence.
type S2SResponseTranscriptDelta ¶
type S2SResponseTranscriptDelta struct {
Type S2SEventType `json:"type"`
Sequence int `json:"sequence"`
Text string `json:"text"`
}
S2SResponseTranscriptDelta is a piece of the text of the answer being spoken, for captions and logs.
func (S2SResponseTranscriptDelta) Validate ¶
func (e S2SResponseTranscriptDelta) Validate() error
Validate checks the frame tag, sequence and that the delta says something.
type S2SSessionClose ¶
type S2SSessionClose struct {
Type S2SControlType `json:"type"`
}
S2SSessionClose asks the server to end the session with a terminal session.closed frame.
func (S2SSessionClose) Validate ¶
func (c S2SSessionClose) Validate() error
Validate checks the frame tag.
type S2SSessionClosed ¶
type S2SSessionClosed struct {
Type S2SEventType `json:"type"`
Usage Usage `json:"usage"`
}
S2SSessionClosed is the clean terminal frame carrying final usage.
func (S2SSessionClosed) Validate ¶
func (e S2SSessionClosed) Validate() error
Validate checks the frame tag and usage.
type S2SSessionConfigure ¶
type S2SSessionConfigure struct {
Type S2SControlType `json:"type"`
Routing Routing `json:"routing"`
Audio S2SAudioConfig `json:"audio"`
// Language is an optional hint: auto routing ranks candidates on that
// language's board and the relay picks a voice curated for it.
Language string `json:"language,omitempty"`
// Voice is optional: in auto mode the party that picks the provider picks
// a default voice for it.
Voice string `json:"voice,omitempty"`
// Instructions is the system prompt the model speaks under.
Instructions string `json:"instructions,omitempty"`
// Temperature is the sampling temperature, 0 to 2 inclusive; omitted
// leaves the vendor default.
Temperature *float64 `json:"temperature,omitempty"`
// ThinkingLevel asks a Gemini Live model to think harder before it speaks
// (low, medium, high). It reaches only the models that take one: the
// adapter supplies it where the service demands it and drops it where the
// service refuses it, so this is a request, not an instruction.
ThinkingLevel string `json:"thinking_level,omitempty"`
}
S2SSessionConfigure opens a speech-to-speech session. Voice, language, instructions and temperature are session intent: they ride this frame and the idempotency hash, and later frames cannot change them.
func (S2SSessionConfigure) Validate ¶
func (c S2SSessionConfigure) Validate() error
Validate checks the frame tag, routing, both audio formats, the instructions bound and the temperature range. The routing must already be normalized.
type S2SSessionReady ¶
type S2SSessionReady struct {
Type S2SEventType `json:"type"`
RequestID string `json:"request_id"`
Route Route `json:"route"`
}
S2SSessionReady confirms admission and reports the concrete route. It is always the first event frame; the client must not send audio before it.
func (S2SSessionReady) Validate ¶
func (e S2SSessionReady) Validate() error
Validate checks the frame tag, request id, and route.
type S2SUsageUpdated ¶
type S2SUsageUpdated struct {
Type S2SEventType `json:"type"`
Usage Usage `json:"usage"`
}
S2SUsageUpdated reports cumulative usage while the session is live. For s2s, duration_ms is connected wall-clock time so far.
func (S2SUsageUpdated) Validate ¶
func (e S2SUsageUpdated) Validate() error
Validate checks the frame tag and usage.
type STTControlType ¶
type STTControlType string
STTControlType tags every client-to-server JSON text frame on GET /v1/stt/stream. Audio input travels in binary frames and is deliberately untyped here. The set is closed.
const ( // STTControlSessionConfigure must be the first text frame on the // socket. Its exact frame bytes are the WebSocket idempotency content // hash (see idempotency.go); later frames are intentionally outside // the hash. STTControlSessionConfigure STTControlType = "session.configure" STTControlInputCommit STTControlType = "input.commit" STTControlSessionClose STTControlType = "session.close" )
type STTEventType ¶
type STTEventType string
STTEventType tags every server-to-client JSON text frame on GET /v1/stt/stream. Exactly one terminal frame — session.closed or error — ends every session. The set is closed.
const ( STTEventSessionReady STTEventType = "session.ready" STTEventTranscriptDelta STTEventType = "transcript.delta" STTEventTranscriptFinal STTEventType = "transcript.final" STTEventUsageUpdated STTEventType = "usage.updated" STTEventSessionClosed STTEventType = "session.closed" STTEventError STTEventType = "error" )
type STTInputCommit ¶
type STTInputCommit struct {
Type STTControlType `json:"type"`
// CommitID optionally names the commit; the transcript.final that
// answers it carries the same id, so a client can tell its answer from
// a final the provider sent on its own. See ValidCommitID for the form.
CommitID string `json:"commit_id,omitempty"`
// contains filtered or unexported fields
}
STTInputCommit marks the end of the audio the client wants finalized. Every commit is answered by exactly one transcript.final, which may be empty when nothing was left to finalize.
func (*STTInputCommit) UnmarshalJSON ¶ added in v0.3.1
func (c *STTInputCommit) UnmarshalJSON(data []byte) error
UnmarshalJSON notes whether the frame carried commit_id. A null commit_id counts as absent, as a null member does everywhere in relayapi.
func (STTInputCommit) Validate ¶
func (c STTInputCommit) Validate() error
Validate checks the frame tag and, when present, the commit id.
type STTOptions ¶
type STTOptions struct {
Diarization *bool `json:"diarization,omitempty"`
// LanguageIdentification asks for spoken-language labels on streaming
// transcript segments. Omitted and false both preserve legacy output.
LanguageIdentification *bool `json:"language_identification,omitempty"`
Keywords []string `json:"keywords,omitempty"`
NoiseReduction *bool `json:"noise_reduction,omitempty"`
// WordTimestamps asks for per-word start/end timings on the batch result
// (TranscriptionResponse.Words). A pointer like Diarization: nil is
// silence, false is a statement.
WordTimestamps *bool `json:"word_timestamps,omitempty"`
// Translation asks for the spoken audio translated into another
// language, returned BESIDE the transcript: `text` stays the original
// words so a caller that ignores translation reads exactly what it read
// before, and the translated words ride a separate `translation` field.
// Fails closed like every canonical ask: a route that cannot translate
// is refused with capability_unsupported naming "translation".
Translation *STTTranslation `json:"translation,omitempty"`
ProviderOptions map[string]map[string]any `json:"provider_options,omitempty"`
}
STTOptions carries caller transcription options for both STT surfaces.
func (*STTOptions) Diarize ¶
func (o *STTOptions) Diarize() bool
Diarize reports whether the caller asked for speaker labels.
func (*STTOptions) GetKeywords ¶
func (o *STTOptions) GetKeywords() []string
GetKeywords returns the caller's vocabulary-biasing terms, trimmed.
func (*STTOptions) IdentifyLanguage ¶ added in v0.3.1
func (o *STTOptions) IdentifyLanguage() bool
IdentifyLanguage reports whether the caller asked for language labels.
func (*STTOptions) IsZero ¶
func (o *STTOptions) IsZero() bool
IsZero reports whether the caller asked for nothing.
func (*STTOptions) ReduceNoise ¶
func (o *STTOptions) ReduceNoise() bool
ReduceNoise reports whether the caller asked for audio enhancement.
func (*STTOptions) TranslationTarget ¶
func (o *STTOptions) TranslationTarget() string
TranslationTarget returns the trimmed target language, or "" when the caller asked for no translation.
func (*STTOptions) Validate ¶
func (o *STTOptions) Validate() error
Validate checks shape and bounds. Names must arrive lower case: the idempotency content hash covers the request bytes as sent, so one intent must have one spelling.
func (*STTOptions) WantsWordTimestamps ¶
func (o *STTOptions) WantsWordTimestamps() bool
WantsWordTimestamps reports whether the caller asked for per-word timings.
type STTSessionClose ¶
type STTSessionClose struct {
Type STTControlType `json:"type"`
}
STTSessionClose asks the server to finish outstanding transcripts and end the session with a terminal session.closed frame.
func (STTSessionClose) Validate ¶
func (c STTSessionClose) Validate() error
Validate checks the frame tag.
type STTSessionClosed ¶
type STTSessionClosed struct {
Type STTEventType `json:"type"`
Usage Usage `json:"usage"`
}
STTSessionClosed is the clean terminal frame carrying final usage.
func (STTSessionClosed) Validate ¶
func (e STTSessionClosed) Validate() error
Validate checks the frame tag and usage.
type STTSessionConfigure ¶
type STTSessionConfigure struct {
Type STTControlType `json:"type"`
Routing Routing `json:"routing"`
Audio AudioConfig `json:"audio"`
Language string `json:"language,omitempty"`
Options *STTOptions `json:"options,omitempty"`
}
STTSessionConfigure opens a streaming transcription. Audio describes the raw binary frames the client will send: streamed audio has no container, so the format must be declared up front.
func (STTSessionConfigure) Validate ¶
func (c STTSessionConfigure) Validate() error
Validate checks the frame tag, routing, declared audio format, and option asks. The routing must already be normalized.
type STTSessionReady ¶
type STTSessionReady struct {
Type STTEventType `json:"type"`
RequestID string `json:"request_id"`
Route Route `json:"route"`
// CommitIDs is true when the server echoes each input.commit's commit_id
// on the transcript.final that answers it, so a client can choose
// correlated commits up front instead of guessing. False and absent both
// mean no echo.
CommitIDs bool `json:"commit_ids,omitempty"`
}
STTSessionReady confirms admission and reports the concrete route. It is always the first event frame; the client must not send audio before it.
func (STTSessionReady) Validate ¶
func (e STTSessionReady) Validate() error
Validate checks the frame tag, request id, and route.
type STTTranscriptDelta ¶
type STTTranscriptDelta struct {
Type STTEventType `json:"type"`
Text string `json:"text"`
// Translation is the interim translation of the current span, present
// only on a session that asked for one. It trails Text: the vendor
// translates words after it recognises them, so a delta may carry
// original words whose translation has not arrived yet, or only a
// translation of words already recognised.
Translation string `json:"translation,omitempty"`
// Segments attributes the hypothesis to speakers or spoken languages when
// requested and supported. It splits on changes in either requested
// label and carries a span when both ends are measured. A later delta or
// final may change any provisional label.
Segments []TranscriptDeltaSegment `json:"segments,omitempty"`
}
STTTranscriptDelta is an interim hypothesis; later deltas and the next transcript.final supersede it.
func (STTTranscriptDelta) Validate ¶
func (e STTTranscriptDelta) Validate() error
Validate checks the frame tag, segments, and that the delta says something — empty interim hypotheses are dropped at normalization, never forwarded. On a translating session a delta that advances only the translation is something.
type STTTranscriptFinal ¶
type STTTranscriptFinal struct {
Type STTEventType `json:"type"`
Text string `json:"text"`
Segments []TranscriptSegment `json:"segments,omitempty"`
// Speaker labels the whole finalized turn; per-span attribution rides
// Segments[].Speaker.
Speaker string `json:"speaker,omitempty"`
// Translation is the finalized translation delivered with this span,
// present only on a session that asked for one. Text stays the original
// words. The vendor's translation trails its transcript, so the last
// words of a span can be translated in the NEXT final's Translation; a
// caller rendering captions concatenates finals rather than pairing them
// one to one.
Translation string `json:"translation,omitempty"`
// CommitID is the id of the input.commit this final answers, present
// only when that commit carried one. A final the provider sent with no
// commit pending carries none.
CommitID string `json:"commit_id,omitempty"`
// Interim marks an interim final: the provider closed part of a long
// segment that is still being spoken, and more of the same segment
// follows. It never answers an input.commit, so it never carries a
// commit_id; the segment's last final does. Absent on every other final.
Interim bool `json:"interim,omitempty"`
}
STTTranscriptFinal is a finalized span of transcript with optional time-aligned segments.
func (STTTranscriptFinal) Validate ¶
func (e STTTranscriptFinal) Validate() error
Validate checks the frame tag, segments and, when present, the commit id. Text may be empty: a finalized span of silence is legitimate.
type STTTranslation ¶
type STTTranslation struct {
// TargetLanguage is a BCP-47 tag ("es", "pt-BR", "zh-Hans"). Adapters
// pass the primary subtag in the vendor's own spelling.
TargetLanguage string `json:"target_language"`
}
STTTranslation names the language the transcript is translated into. One way only: the source language is whatever was spoken (or the request's language hint), so there is nothing else for a caller to say.
type STTUsageUpdated ¶
type STTUsageUpdated struct {
Type STTEventType `json:"type"`
Usage Usage `json:"usage"`
}
STTUsageUpdated reports cumulative usage while the stream is live so callers can watch spend before the terminal frame.
func (STTUsageUpdated) Validate ¶
func (e STTUsageUpdated) Validate() error
Validate checks the frame tag and usage.
type SampleRateRange ¶
SampleRateRange is an inclusive set of sample rates accepted by one audio format. It is used instead of enumerating every integer rate for providers that accept a bounded continuous range.
type SpeechRequest ¶
type SpeechRequest struct {
Routing Routing `json:"routing"`
Input string `json:"input"`
Voice string `json:"voice,omitempty"`
Language string `json:"language,omitempty"`
Audio AudioConfig `json:"audio"`
// Options carries per-provider synthesis settings. Omitempty keeps every
// request that predates it byte-identical on the connector hop.
Options *TTSOptions `json:"options,omitempty"`
}
SpeechRequest is the POST /v1/tts/speech body. The response is a raw audio stream; the route and billed character count come back in headers (Speko-Provider, Speko-Model, Speko-Region, Speko-Usage-Characters) because a byte stream has no place for a JSON envelope. Language is an optional hint, like the STT shapes: auto routing ranks candidates on that language's board and the relay picks a voice curated for it; omitted means English, which was the only behavior before the field existed.
func (SpeechRequest) Validate ¶
func (r SpeechRequest) Validate() error
Validate checks routing, input, and the requested output format. Voice is optional: in auto mode the party that picks the provider picks a default voice for it. Callers normalize Routing with NormalizeDefault first.
type StopReason ¶
type StopReason string
StopReason explains why generation ended. The set is closed.
const ( StopReasonStop StopReason = "stop" StopReasonMaxOutputTokens StopReason = "max_output_tokens" StopReasonToolCall StopReason = "tool_call" )
type StreamEvent ¶
type StreamEvent interface {
Event() string
}
StreamEvent is implemented by every SSE data payload. Event returns the SSE event name the payload travels under.
type TTSControlType ¶
type TTSControlType string
TTSControlType tags every client-to-server JSON text frame on GET /v1/tts/stream. The set is closed.
const ( // TTSControlSessionConfigure must be the first text frame on the // socket. Its exact frame bytes are the WebSocket idempotency content // hash (see idempotency.go); later frames are intentionally outside // the hash. TTSControlSessionConfigure TTSControlType = "session.configure" TTSControlInputAppend TTSControlType = "input.append" TTSControlInputCommit TTSControlType = "input.commit" TTSControlInputCancel TTSControlType = "input.cancel" TTSControlSessionClose TTSControlType = "session.close" )
type TTSEventType ¶
type TTSEventType string
TTSEventType tags every server-to-client JSON text frame on GET /v1/tts/stream. Synthesized audio travels in binary frames between utterance.started and utterance.done, and utterance.timings — when the caller's model measures speech timings and the client asked for them — travels alongside that audio, before the utterance.done that closes it. Exactly one terminal frame — session.closed or error — ends every session. The set is closed.
const ( TTSEventSessionReady TTSEventType = "session.ready" TTSEventUtteranceStarted TTSEventType = "utterance.started" TTSEventUtteranceTimings TTSEventType = "utterance.timings" TTSEventUtteranceDone TTSEventType = "utterance.done" TTSEventUsageUpdated TTSEventType = "usage.updated" TTSEventSessionClosed TTSEventType = "session.closed" TTSEventError TTSEventType = "error" )
type TTSInputAppend ¶
type TTSInputAppend struct {
Type TTSControlType `json:"type"`
Text string `json:"text"`
}
TTSInputAppend adds text to the utterance being assembled. Characters are counted against the reserved budget when appended, so an over-budget append fails before any provider work happens.
func (TTSInputAppend) Validate ¶
func (c TTSInputAppend) Validate() error
Validate checks the frame tag and that the append carries text.
type TTSInputCancel ¶
type TTSInputCancel struct {
Type TTSControlType `json:"type"`
}
TTSInputCancel abandons uncommitted appended text and any in-flight synthesis for the current utterance.
func (TTSInputCancel) Validate ¶
func (c TTSInputCancel) Validate() error
Validate checks the frame tag.
type TTSInputCommit ¶
type TTSInputCommit struct {
Type TTSControlType `json:"type"`
}
TTSInputCommit finalizes the appended text as one utterance and starts synthesis.
func (TTSInputCommit) Validate ¶
func (c TTSInputCommit) Validate() error
Validate checks the frame tag.
type TTSOptions ¶
type TTSOptions struct {
ProviderOptions map[string]map[string]any `json:"provider_options,omitempty"`
}
TTSOptions carries caller synthesis options for both TTS surfaces: the POST /v1/tts/speech body and the streaming session.configure frame.
There are no canonical asks yet, only ProviderOptions: the vendor's OWN settings, namespaced by provider name, e.g. {"cartesia": {"normalization": "en-IN"}, "elevenlabs": {"stability": 0.4}}. Settings addressed to a provider the request does not reach are ignored by design, so a caller can tune two vendors and let routing decide which one reads its own. Settings addressed to the routed provider fail closed: a key that provider's route does not forward is refused by name rather than accepted and dropped.
func (*TTSOptions) IsZero ¶
func (o *TTSOptions) IsZero() bool
IsZero reports whether the caller asked for nothing.
func (*TTSOptions) Provider ¶
func (o *TTSOptions) Provider(name string) map[string]any
Provider returns the caller's settings for one provider. Nil when nothing was sent, so callers can range over it unconditionally.
func (*TTSOptions) UnmarshalJSON ¶
func (o *TTSOptions) UnmarshalJSON(data []byte) error
UnmarshalJSON keeps the options object closed. encoding/json would drop a misspelled member, leaving empty options that validate and synthesize with vendor defaults: a 200 that silently did not do what was asked.
func (*TTSOptions) Validate ¶
func (o *TTSOptions) Validate() error
Validate checks shape and bounds. Names must arrive lower case and trimmed: the idempotency content hash covers the request bytes as sent, so one intent must have one spelling, and the connector's normalization (which folds and trims) must be a no-op on anything admitted here. Whether a provider accepts a named setting is a routing-time question the Router answers per route.
type TTSOptionsDecodeError ¶
type TTSOptionsDecodeError struct {
Err error
}
TTSOptionsDecodeError is an options object the strict decoder refused, typically a misspelled member such as "provider_option". The edges match it to answer invalid_request naming the problem rather than "not valid JSON".
func (*TTSOptionsDecodeError) Error ¶
func (e *TTSOptionsDecodeError) Error() string
func (*TTSOptionsDecodeError) Unwrap ¶
func (e *TTSOptionsDecodeError) Unwrap() error
type TTSSessionClose ¶
type TTSSessionClose struct {
Type TTSControlType `json:"type"`
}
TTSSessionClose asks the server to finish outstanding synthesis and end the session with a terminal session.closed frame.
func (TTSSessionClose) Validate ¶
func (c TTSSessionClose) Validate() error
Validate checks the frame tag.
type TTSSessionClosed ¶
type TTSSessionClosed struct {
Type TTSEventType `json:"type"`
Usage Usage `json:"usage"`
}
TTSSessionClosed is the clean terminal frame carrying final usage.
func (TTSSessionClosed) Validate ¶
func (e TTSSessionClosed) Validate() error
Validate checks the frame tag and usage.
type TTSSessionConfigure ¶
type TTSSessionConfigure struct {
Type TTSControlType `json:"type"`
Routing Routing `json:"routing"`
Voice string `json:"voice,omitempty"`
Language string `json:"language,omitempty"`
Audio AudioConfig `json:"audio"`
// Options carries per-provider synthesis settings for the whole session.
Options *TTSOptions `json:"options,omitempty"`
}
TTSSessionConfigure opens a streaming synthesis session. Language is an optional hint, like the STT shapes: auto routing ranks candidates on that language's board and the relay picks a voice curated for it; omitted means English, which was the only behavior before the field existed.
func (TTSSessionConfigure) Validate ¶
func (c TTSSessionConfigure) Validate() error
Validate checks the frame tag, routing, and requested output format. The routing must already be normalized; the idempotency hash covers the raw frame bytes as sent, before any normalization.
type TTSSessionReady ¶
type TTSSessionReady struct {
Type TTSEventType `json:"type"`
RequestID string `json:"request_id"`
Route Route `json:"route"`
Audio *AudioConfig `json:"audio,omitempty"`
}
TTSSessionReady confirms admission and reports the concrete route. It is always the first event frame; the client must not append text before it. Audio is the format the binary audio frames will carry. Servers that predate the field omit it and do not report the format: depending on their version they send the requested format or pcm_s16le 24 kHz mono, so a client that must be certain on such a server requests pcm_s16le 24 kHz mono.
func (TTSSessionReady) Validate ¶
func (e TTSSessionReady) Validate() error
Validate checks the frame tag, request id, and route.
type TTSUsageUpdated ¶
type TTSUsageUpdated struct {
Type TTSEventType `json:"type"`
Usage Usage `json:"usage"`
}
TTSUsageUpdated reports cumulative usage while the stream is live so callers can watch spend before the terminal frame.
func (TTSUsageUpdated) Validate ¶
func (e TTSUsageUpdated) Validate() error
Validate checks the frame tag and usage.
type TTSUtteranceDone ¶
type TTSUtteranceDone struct {
Type TTSEventType `json:"type"`
Sequence int `json:"sequence"`
}
TTSUtteranceDone marks the end of one utterance's binary audio frames.
func (TTSUtteranceDone) Validate ¶
func (e TTSUtteranceDone) Validate() error
Validate checks the frame tag and sequence.
type TTSUtteranceStarted ¶
type TTSUtteranceStarted struct {
Type TTSEventType `json:"type"`
Sequence int `json:"sequence"`
}
TTSUtteranceStarted announces the binary audio frames for one committed utterance. Sequence is the 1-based utterance index within the session so clients can correlate audio with commits.
func (TTSUtteranceStarted) Validate ¶
func (e TTSUtteranceStarted) Validate() error
Validate checks the frame tag and sequence.
type TTSUtteranceTimings ¶
type TTSUtteranceTimings struct {
Type TTSEventType `json:"type"`
Sequence int `json:"sequence"`
Granularity TimingGranularity `json:"granularity"`
Spans []TimingSpan `json:"spans"`
}
TTSUtteranceTimings carries time-aligned spans for the utterance sharing its sequence number. It is emitted only when the route's model measures timings; a model that does not advertise word_timings or character_timings never sends it.
One utterance may produce SEVERAL of these events, all carrying the same sequence: a long render's spans are flushed as they accumulate rather than held for one frame that could exceed the stream's frame ceiling. The client concatenates them in arrival order. Every event for an utterance arrives before the utterance.done that closes it.
func (TTSUtteranceTimings) Validate ¶
func (e TTSUtteranceTimings) Validate() error
Validate checks the frame tag, sequence, granularity, and every span.
Spans are checked INDIVIDUALLY and never against each other: engines legitimately return adjacent spans that overlap, where one sound is still being articulated as the next begins, and a monotonicity rule would reject those valid frames.
type TimingGranularity ¶
type TimingGranularity string
TimingGranularity says what unit a TimingSpan measures.
Synthesis always reports word. A character-level engine still measures characters, and the adapters still report exactly what it gave them, but the relay groups that reading into words before it reaches a caller — so the fold is written once, here, instead of once per client per provider.
character stays in the set for a reading passed through ungrouped. The set is closed.
const ( TimingGranularityWord TimingGranularity = "word" TimingGranularityCharacter TimingGranularity = "character" )
type TimingSpan ¶
type TimingSpan struct {
Text string `json:"text"`
StartMS int64 `json:"start_ms"`
EndMS int64 `json:"end_ms"`
}
TimingSpan is one time-aligned span of synthesized speech, measured from the start of the utterance. Field names and validation mirror TranscriptSegment: end_ms is an end time, never a duration.
Spans describe the caller's OWN text — a provider that also reports timings over its normalized reading ("five dollars" for "$5") has that reading dropped rather than carried, because a client walking its own string against normalized spans desynchronizes silently.
func (TimingSpan) Validate ¶
func (s TimingSpan) Validate() error
Validate checks that the span is a non-negative, ordered range.
type TranscriptDeltaSegment ¶ added in v0.3.1
type TranscriptDeltaSegment struct {
Text string `json:"text"`
StartMS *int64 `json:"start_ms,omitempty"`
EndMS *int64 `json:"end_ms,omitempty"`
// Speaker is the vendor's own label, carried verbatim.
Speaker string `json:"speaker,omitempty"`
// Language is the provider's provisional BCP-47 label, when requested and known.
Language string `json:"language,omitempty"`
}
TranscriptDeltaSegment is a speaker or language run in a provisional transcript. It carries its span only when the provider measured both ends.
func (TranscriptDeltaSegment) Validate ¶ added in v0.3.1
func (s TranscriptDeltaSegment) Validate() error
Validate checks that the span, when present, is whole, non-negative and ordered.
type TranscriptSegment ¶
type TranscriptSegment struct {
Text string `json:"text"`
StartMS int64 `json:"start_ms"`
EndMS int64 `json:"end_ms"`
// Speaker is the vendor's own label, carried verbatim.
Speaker string `json:"speaker,omitempty"`
// Language is the provider's BCP-47 spoken-language label, when requested and known.
Language string `json:"language,omitempty"`
}
TranscriptSegment is one time-aligned span of the transcript.
func (TranscriptSegment) Validate ¶
func (s TranscriptSegment) Validate() error
Validate checks that the span is a non-negative, ordered range.
type TranscriptWord ¶
type TranscriptWord struct {
Text string `json:"text"`
StartMS int64 `json:"start_ms"`
EndMS int64 `json:"end_ms"`
Speaker string `json:"speaker,omitempty"`
}
TranscriptWord is one word of the transcript with its own timing. Present only when the request asked for word_timestamps and the routed model advertises it; the vendor's own speaker label rides along when the request also asked for diarization.
func (TranscriptWord) Validate ¶
func (w TranscriptWord) Validate() error
Validate checks that the word is a non-negative, ordered range with text.
type TranscriptionRequest ¶
type TranscriptionRequest struct {
Routing Routing `json:"routing"`
Language string `json:"language,omitempty"`
Options *STTOptions `json:"options,omitempty"`
}
TranscriptionRequest is the JSON metadata part of a batch transcription. The audio container itself (WAV/PCM headers at launch) declares the media format, so the metadata carries only routing and options.
func (TranscriptionRequest) Validate ¶
func (r TranscriptionRequest) Validate() error
Validate checks the metadata part. Callers normalize Routing with NormalizeDefault first — an omitted routing object defaults to {mode: auto, objective: balanced}.
type TranscriptionResponse ¶
type TranscriptionResponse struct {
Text string `json:"text"`
Segments []TranscriptSegment `json:"segments,omitempty"`
// Words are per-word timings, present only when word_timestamps was asked
// for. Omitted otherwise, so every existing response is byte-identical.
Words []TranscriptWord `json:"words,omitempty"`
// Translation is the transcript translated into
// options.translation.target_language, present only when translation
// was asked for. Text stays the ORIGINAL spoken words, so a caller that
// never asks reads a byte-identical response. Translated words carry no
// timings (the vendor generates them after the words they translate),
// so there are no translated segments.
Translation string `json:"translation,omitempty"`
Route Route `json:"route"`
Usage Usage `json:"usage"`
}
TranscriptionResponse is the batch transcription result. Usage carries the billed duration; there is deliberately no STT usage header.
func (TranscriptionResponse) Validate ¶
func (r TranscriptionResponse) Validate() error
Validate checks segments, words, route, and usage. Text may be empty: silent audio legitimately transcribes to nothing.
type Usage ¶
type Usage struct {
// Incomplete means a terminal provider response omitted or contradicted
// billing quantities. Missing evidence must not be treated as zero usage.
Incomplete bool `json:"incomplete,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
Characters int64 `json:"characters,omitempty"`
InputTokens int64 `json:"input_tokens,omitempty"`
CachedInputTokens int64 `json:"cached_input_tokens,omitempty"`
CacheWrite5mTokens int64 `json:"cache_write_5m_tokens,omitempty"`
CacheWrite1hTokens int64 `json:"cache_write_1h_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`
// ToolCalls counts billable hosted tool invocations (web search) a
// delegated GPT-Live backend performed. Zero for every other route.
ToolCalls int64 `json:"tool_calls,omitempty"`
}
Usage reports normalized, provider-neutral quantities for one request or stream. Only the lines relevant to the request's kind are set; zero lines are omitted on the wire.
Split lines are mutually exclusive by contract: a token counted in cached_input_tokens is not repeated in input_tokens, and a reasoning token is not repeated in output_tokens. The splits therefore always sum to the totals — see TotalInputTokens and TotalOutputTokens. Providers that report no split report all-uncached / all-visible: everything lands in input_tokens and output_tokens with the split lines at zero.
func (Usage) TotalInputTokens ¶
TotalInputTokens is the full prompt size: ordinary input, cache reads, and cache writes. It is a sum precisely because the split lines are mutually exclusive.
func (Usage) TotalOutputTokens ¶
TotalOutputTokens is the full generation size: visible output plus reasoning. It is a sum precisely because the split lines are mutually exclusive.