customize

package
v0.81.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 8 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package customize defines Words, Replacements and shared recognition hints.

Package customize defines SpeechKit's public Words/Replacements contract.

Stability: Stable — no breaking change without a minor version bump and a changelog callout.

Index

Constants

View Source
const PackSchemaVersion = "speechkit.customization.pack.v1"

PackSchemaVersion is the only non-empty schema_version ValidatePack accepts.

Variables

This section is empty.

Functions

func BuildKeyterms added in v0.76.2

func BuildKeyterms(words []Word) []string

BuildKeyterms returns enabled canonical terms and their pronunciation aliases.

func BuildPrompt added in v0.76.2

func BuildPrompt(words []Word) string

BuildPrompt renders enabled canonical terms as a transcript-style prompt.

func BuildVoiceAgentHint added in v0.76.2

func BuildVoiceAgentHint(words []Word) string

BuildVoiceAgentHint renders enabled terms for recognition and responses.

func CanonicalTerms added in v0.76.2

func CanonicalTerms(words []Word) []string

CanonicalTerms returns distinct enabled canonical terms in input order.

func FoldVocabulary added in v0.61.10

func FoldVocabulary(words []Word, replacements []Replacement) (folded []Word, extras []Replacement)

FoldVocabulary attaches synonym/substitution rewrites whose output matches a Word onto that Word's sounds_like list. Remaining replacements are extras (punctuation, regex, snippets, commands).

func MaterializeVocabulary added in v0.61.10

func MaterializeVocabulary(words []Word, extras []Replacement) (merged []Word, replacements []Replacement)

MaterializeVocabulary merges Words and rebuilds alias replacements from sounds_like. extras must already be non-alias rules; derived aliases that also appear in extras are dropped so Words stay the source of truth.

func NormalizeAliasList added in v0.61.9

func NormalizeAliasList(term string, aliases []string) []string

NormalizeAliasList trims, drops empties, drops the canonical term, and de-duplicates case-insensitively while keeping first-seen spelling.

func NormalizeLanguage

func NormalizeLanguage(language string) string

NormalizeLanguage reduces a locale such as "de-DE" or "en_US" to its lowercase two-letter primary language ("de", "en"). Empty, "auto", and "multi" mean unspecified and return "", which matches every language.

func ReplacementIdentityKey added in v0.61.9

func ReplacementIdentityKey(replacement Replacement) string

ReplacementIdentityKey is the authoring identity for a Replacement. Output is intentionally not part of the key: many spoken forms may rewrite to the same canonical word.

func StableID

func StableID(prefix string, parts ...string) string

StableID derives a deterministic "<prefix>_<16 hex chars>" identifier from a SHA-256 over the trimmed, lowercased parts, so equal authoring identities always map to the same ID.

func ValidatePack

func ValidatePack(pack Pack) error

ValidatePack validates a pack for import: SchemaVersion must be empty or PackSchemaVersion, every Word and Replacement must pass its validator, Lexicons and Rulesets need a Name, and Attachments must be valid JSON when present.

func ValidateReplacement

func ValidateReplacement(replacement Replacement) error

ValidateReplacement returns an error for the first invalid field of replacement: an unknown Kind, Stage, Match.Type, or mode, a blank Match.Pattern, or a synonym without Output.Text.

func ValidateWord

func ValidateWord(word Word) error

ValidateWord returns an error when word has a blank Term or a negative Weight.

func WordIdentityKey added in v0.61.9

func WordIdentityKey(word Word) string

WordIdentityKey is the authoring identity for a Word: language + term.

Types

type Context

type Context struct {
	Mode              Mode       `json:"mode,omitempty"`
	Language          string     `json:"language,omitempty"`
	Stage             Stage      `json:"stage,omitempty"`
	Tags              []string   `json:"tags,omitempty"`
	Persona           string     `json:"persona,omitempty"`
	ActiveTemplateIDs []string   `json:"active_template_ids,omitempty"`
	ScopeOrder        []ScopeRef `json:"scope_order,omitempty"`
}

Context selects the active customization set for one resolve or apply call. Language, Mode, and Stage filter records (language-neutral records and rules without modes always match), Tags activates tagged records whose tags intersect, ActiveTemplateIDs adds Native Template packs, and ScopeOrder lists scope layers from lowest to highest precedence (hosts fall back to DefaultDeviceScopeOrder or DefaultServerScopeOrder when empty). Persona names the active persona for persona-bound collections.

type DictionaryEntry added in v0.76.2

type DictionaryEntry struct {
	Spoken     string
	Canonical  string
	Language   string
	Source     string
	Enabled    bool
	UsageCount int
}

DictionaryEntry is the compatibility projection of a stored vocabulary rule.

func ParseDictionary added in v0.76.2

func ParseDictionary(raw string) []DictionaryEntry

ParseDictionary reads newline-separated terms or spoken => canonical rules. Empty lines and rules with an empty side are discarded.

type Kind

type Kind string

Kind is the closed discriminator that says what a Replacement produces when its match fires. Compare values after NormalizeKind.

const (
	// KindSubstitution rewrites the match to Output.Text; an empty output
	// deletes the match (filler-word stripping).
	KindSubstitution Kind = "substitution"
	// KindSynonym normalizes a spoken or written variant to one preferred
	// form; Output.Text is required.
	KindSynonym Kind = "synonym"
	// KindSnippet expands a short trigger into a static text block.
	KindSnippet Kind = "snippet"
	// KindCommand emits Output.Intent and Payload as an action instead of
	// rewriting text.
	KindCommand Kind = "command"
	// KindTemplate renders Output.Template (Go text/template) for Assist
	// and Summarize flows; it is unrelated to the Native Template catalog.
	KindTemplate Kind = "template"
)

Replacement kinds. The set is closed by the Words and Replacements standard; adding a kind is a standard change, not a local extension.

func NormalizeKind

func NormalizeKind(kind Kind) Kind

NormalizeKind trims and lowercases kind and returns the canonical Kind; unknown kinds return "".

type Lexicon

type Lexicon struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description,omitempty"`
	Language    string    `json:"language,omitempty"`
	WordIDs     []string  `json:"word_ids,omitempty"`
	Tags        []string  `json:"tags,omitempty"`
	Source      string    `json:"source,omitempty"`
	Scope       *ScopeRef `json:"scope,omitempty"`
	Enabled     bool      `json:"enabled"`
	CreatedAt   time.Time `json:"created_at,omitempty"`
	UpdatedAt   time.Time `json:"updated_at,omitempty"`
}

Lexicon is a named collection of Word records referenced by ID. Name is required; a store assigns a StableID when ID is empty.

type ListOptions

type ListOptions struct {
	Language        string
	Mode            Mode
	Stage           Stage
	IncludeDisabled bool
	Source          string
	Tags            []string
}

ListOptions filters store reads of Words, Replacements, Lexicons, and Rulesets within the storage scope carried by the context. Language keeps records of that language plus language-neutral ones (empty keeps all), Mode and Stage apply to Replacements only, Source keeps one origin, and disabled records are omitted unless IncludeDisabled is set. Tags carries the resolve context tags; the resolver re-checks tag matches on returned rows.

type Match

type Match struct {
	Type          MatchType `json:"type"`
	Pattern       string    `json:"pattern"`
	CaseSensitive bool      `json:"case_sensitive,omitempty"`
	WordBoundary  bool      `json:"word_boundary,omitempty"`
}

Match is the trigger of a Replacement. Matching is case-insensitive unless CaseSensitive is set; WordBoundary makes a literal pattern match whole words only (phrase and spoken-alias patterns always do).

type MatchType

type MatchType string

MatchType says how Match.Pattern is interpreted when a rule compiles.

const (
	// MatchLiteral matches the pattern verbatim, on word boundaries only
	// when Match.WordBoundary is set.
	MatchLiteral MatchType = "literal"
	// MatchPhrase matches the pattern verbatim and always on word
	// boundaries. It is the default.
	MatchPhrase MatchType = "phrase"
	// MatchRegex compiles the pattern as a Go regular expression.
	MatchRegex MatchType = "regex"
	// MatchSpokenAlias is a word-bounded spoken form (mishear) of a [Word];
	// such rules fold into and derive from Word.SoundsLike.
	MatchSpokenAlias MatchType = "spoken_alias"
)

Match types; NormalizeMatchType treats an empty type as MatchPhrase.

func NormalizeMatchType

func NormalizeMatchType(matchType MatchType) MatchType

NormalizeMatchType trims and lowercases matchType and returns the canonical MatchType. Empty defaults to MatchPhrase; unknown types return "".

type Mode

type Mode string

Mode is one of SpeechKit's three voice modes. A Replacement lists the modes it applies to; an empty list means every mode.

const (
	ModeDictation  Mode = "dictation"
	ModeAssist     Mode = "assist"
	ModeVoiceAgent Mode = "voice_agent"
)

Voice modes; NormalizeMode also accepts common aliases.

func NormalizeMode

func NormalizeMode(mode Mode) Mode

NormalizeMode maps mode and its accepted aliases ("dictate", "transcribe", "stt", "voice-agent", "realtime_voice", ...) to the canonical Mode; unknown values return "".

func WordSynonymModes added in v0.61.10

func WordSynonymModes() []Mode

WordSynonymModes is the mode set for aliases derived from a Word.

type Pack

type Pack struct {
	SchemaVersion string          `json:"schema_version"`
	ID            string          `json:"id,omitempty"`
	Name          string          `json:"name,omitempty"`
	Description   string          `json:"description,omitempty"`
	Words         []Word          `json:"words,omitempty"`
	Replacements  []Replacement   `json:"replacements,omitempty"`
	Lexicons      []Lexicon       `json:"lexicons,omitempty"`
	Rulesets      []Ruleset       `json:"rulesets,omitempty"`
	Attachments   json.RawMessage `json:"attachments,omitempty"`
	CreatedAt     time.Time       `json:"created_at,omitempty"`
}

Pack is the portable, versioned interchange format for Words, Replacements, Lexicons, Rulesets, and free-form JSON Attachments. SchemaVersion must be empty or PackSchemaVersion. Imports derive a "pack:<id>" Source from ID (or Name), so re-importing a pack replaces only the rows of the same scope, source, and language.

type ProviderBias added in v0.76.2

type ProviderBias struct {
	Prompt     string
	Keyterms   []string
	ByProvider map[string]provideropts.Values
	Preview    []ProviderBiasPreview
}

ProviderBias describes vocabulary hints and their supported provider mappings.

func BuildProviderBias added in v0.76.2

func BuildProviderBias(words []Word) ProviderBias

BuildProviderBias describes the STT mappings available for enabled words.

func BuildProviderBiasForManifest added in v0.76.3

func BuildProviderBiasForManifest(words []Word, manifest provideropts.ProviderOptionManifest) ProviderBias

BuildProviderBiasForManifest previews the dictionary channel an adapter's concrete model/transport manifest selects, including custom providers.

func BuildProviderBiasForModality added in v0.76.2

func BuildProviderBiasForModality(words []Word, modality string) ProviderBias

BuildProviderBiasForModality describes vocabulary mappings for a modality.

type ProviderBiasPreview added in v0.76.2

type ProviderBiasPreview struct {
	Provider string
	Modality string
	Strategy string
	Native   bool
	Keyterms []string
	Prompt   string
}

ProviderBiasPreview describes a provider's vocabulary bias strategy.

type RecognitionHints added in v0.76.2

type RecognitionHints struct {
	Prompt   string   `json:"prompt,omitempty"`
	Keyterms []string `json:"keyterms,omitempty"`
}

RecognitionHints carries dictionary-derived hints separately from explicit request hints, so vocabulary_bias=false can suppress only the dictionary.

func BuildRecognitionHints added in v0.76.2

func BuildRecognitionHints(words []Word) RecognitionHints

BuildRecognitionHints renders enabled Words for batch and streaming recognition. Provider adapters choose prompt or native keyterms according to their manifest.

type ReplaceOptions

type ReplaceOptions struct {
	Language string
	Source   string
}

ReplaceOptions addresses one replace or import slice: only rows sharing the storage scope of the context, Language, and Source are deleted and rewritten. An empty Source means "settings".

type Replacement

type Replacement struct {
	ID         string            `json:"id"`
	Kind       Kind              `json:"kind"`
	Match      Match             `json:"match"`
	Output     ReplacementOutput `json:"output"`
	Language   string            `json:"language,omitempty"`
	Modes      []Mode            `json:"modes,omitempty"`
	Stage      Stage             `json:"stage"`
	Priority   int               `json:"priority,omitempty"`
	Tags       []string          `json:"tags,omitempty"`
	Source     string            `json:"source,omitempty"`
	Scope      *ScopeRef         `json:"scope,omitempty"`
	Enabled    bool              `json:"enabled"`
	UsageCount int               `json:"usage_count,omitempty"`
	CreatedAt  time.Time         `json:"created_at,omitempty"`
	UpdatedAt  time.Time         `json:"updated_at,omitempty"`
}

Replacement is a deterministic transformation rule: when Match fires at Stage in one of Modes (empty means every mode), produce Output according to Kind. Rules apply in descending Priority with ID as tie-breaker; a tagged rule is active only when its Tags intersect the resolve Context. Scope says where the rule applies and Source where it came from.

func MergeReplacements added in v0.61.9

func MergeReplacements(replacements []Replacement) []Replacement

MergeReplacements collapses exact identity duplicates. Distinct match patterns that rewrite to the same output are kept.

func SynonymReplacement added in v0.61.9

func SynonymReplacement(term, alias, language, source string) Replacement

SynonymReplacement builds the derived rewrite for a Word alias.

func WithDefaultsReplacement

func WithDefaultsReplacement(replacement Replacement) Replacement

WithDefaultsReplacement returns replacement with Kind, Stage, Match.Type, Match.Pattern, and Language normalized, Source defaulted to "settings", and, when ID is empty, an ID derived with StableID from kind, language, stage, match type, and pattern. Output is not part of that identity.

type ReplacementOutput

type ReplacementOutput struct {
	Text     string         `json:"text,omitempty"`
	Intent   string         `json:"intent,omitempty"`
	Template string         `json:"template,omitempty"`
	Payload  map[string]any `json:"payload,omitempty"`
}

ReplacementOutput is what a Replacement produces; which fields matter depends on its Kind. Text is the rewrite for substitution, synonym, and snippet rules, Intent and Payload describe a command action, and Template is a Go text/template (data: ID, Kind, Input, Match, Intent, Payload) that takes precedence over Text when set.

type Ruleset

type Ruleset struct {
	ID             string    `json:"id"`
	Name           string    `json:"name"`
	Description    string    `json:"description,omitempty"`
	Language       string    `json:"language,omitempty"`
	ReplacementIDs []string  `json:"replacement_ids,omitempty"`
	Tags           []string  `json:"tags,omitempty"`
	Source         string    `json:"source,omitempty"`
	Scope          *ScopeRef `json:"scope,omitempty"`
	Enabled        bool      `json:"enabled"`
	CreatedAt      time.Time `json:"created_at,omitempty"`
	UpdatedAt      time.Time `json:"updated_at,omitempty"`
}

Ruleset is a named collection of Replacement records referenced by ID. Name is required; a store assigns a StableID when ID is empty.

type ScopeKind

type ScopeKind string

ScopeKind is the layer a customization record belongs to. The resolver walks a Context.ScopeOrder from lowest to highest precedence and lets later layers override earlier ones by identity.

const (
	// ScopeBuiltin holds the curated Native Template packs SpeechKit ships.
	ScopeBuiltin ScopeKind = "builtin"
	// ScopeApp holds records the embedding application provides.
	ScopeApp ScopeKind = "app"
	// ScopeInstall holds records of one installation, keyed by install ID.
	ScopeInstall ScopeKind = "install"
	// ScopeOrg holds records of one organization (tenant); "tenant" is an
	// accepted alias.
	ScopeOrg ScopeKind = "org"
	// ScopeWorkspace holds records of one named workspace.
	ScopeWorkspace ScopeKind = "workspace"
	// ScopeUser holds records of one user.
	ScopeUser ScopeKind = "user"
	// ScopeSession holds records of one session and overrides every other
	// layer.
	ScopeSession ScopeKind = "session"
)

Scope layers in default precedence order, lowest first. Org, workspace, user, and session layers address one concrete instance through ScopeRef.Key or the caller's storage scope.

func NormalizeScopeKind

func NormalizeScopeKind(kind ScopeKind) ScopeKind

NormalizeScopeKind trims and lowercases kind and returns the canonical ScopeKind; "tenant" maps to ScopeOrg. Unknown kinds return "".

type ScopeRef

type ScopeRef struct {
	Kind ScopeKind `json:"kind"`
	Key  string    `json:"key,omitempty"`
}

ScopeRef selects one customization layer. Key names the concrete install, org, workspace, user, or session; when empty, the resolver derives it from the caller's storage scope where it can and skips the layer otherwise.

func DefaultDeviceScopeOrder

func DefaultDeviceScopeOrder() []ScopeRef

DefaultDeviceScopeOrder returns the Device host precedence builtin < app < install < user < session, lowest first: later layers override earlier ones by identity.

func DefaultServerScopeOrder

func DefaultServerScopeOrder() []ScopeRef

DefaultServerScopeOrder returns the Server host precedence builtin < app < install < org < user < session, lowest first.

func NormalizeScopeRef

func NormalizeScopeRef(ref ScopeRef) ScopeRef

NormalizeScopeRef canonicalizes ref.Kind with NormalizeScopeKind and trims ref.Key.

type Stage

type Stage string

Stage names the point in the voice pipeline at which a Replacement applies. A resolve Context with a Stage keeps only rules of that stage.

const (
	// StagePreRecognitionCleanup cleans recognition input before it is
	// recognized.
	StagePreRecognitionCleanup Stage = "pre_recognition_cleanup"
	// StagePostSTT transforms the transcript right after speech-to-text;
	// Dictation and Assist apply this stage, and derived synonym rules
	// default to it.
	StagePostSTT Stage = "post_stt"
	// StagePostLLM transforms text generated by an LLM step.
	StagePostLLM Stage = "post_llm"
	// StageOutput transforms the final text before it leaves SpeechKit.
	StageOutput Stage = "output"
)

Pipeline stages in processing order.

func NormalizeStage

func NormalizeStage(stage Stage) Stage

NormalizeStage trims and lowercases stage and returns the canonical Stage; unknown stages return "".

type Word

type Word struct {
	ID         string    `json:"id"`
	Term       string    `json:"term"`
	SoundsLike []string  `json:"sounds_like,omitempty"`
	Language   string    `json:"language,omitempty"`
	Weight     float64   `json:"weight,omitempty"`
	Tags       []string  `json:"tags,omitempty"`
	Scope      *ScopeRef `json:"scope,omitempty"`
	Source     string    `json:"source,omitempty"`
	Enabled    bool      `json:"enabled"`
	UsageCount int       `json:"usage_count,omitempty"`
	CreatedAt  time.Time `json:"created_at,omitempty"`
	UpdatedAt  time.Time `json:"updated_at,omitempty"`
}

Word is declarative recognition knowledge: a term STT and LLM providers should know. It never rewrites text itself; each SoundsLike alias is materialized into a synonym Replacement. Language is a primary-language prefix (empty means all languages), Weight an optional boost (>= 0) mapped to provider scales where supported, Scope says where the Word applies and Source where it came from ("settings", "api", "pack:<id>", and so on).

func MergeWords added in v0.61.9

func MergeWords(words []Word) []Word

MergeWords collapses duplicate terms in the same language. sounds_like and tags are unioned. Duplicate rows are a settings/migration defect, not a supported authoring state.

func WithDefaultsWord

func WithDefaultsWord(word Word) Word

WithDefaultsWord returns word with Term trimmed, Language normalized, Source defaulted to "settings", and, when ID is empty, an ID derived with StableID from language and term.

func WordsFromDictionary added in v0.76.2

func WordsFromDictionary(entries []DictionaryEntry) []Word

WordsFromDictionary converts enabled dictionary entries into framework words.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL