Documentation
¶
Overview ¶
Package inference embedding types define embedding requests and responses.
Package inference errors are stable, typed failures. Callers inspect them with errors.Is and errors.As. Provider adapters map their native failures to these categories; the neutral layer never invents a category.
Retry-After information is preserved where the protocol supplies it, without exposing credentials or remote response bodies.
Package inference generation types define multimodal generation requests and responses. Parts carry text, reasoning, refusal, image, audio, video, file, or opaque provider context. The neutral layer never interprets part payloads beyond bounds and shape validation.
Package inference defines portable, transport-free contracts for inference through a caller-selected provider: generation, streaming generation, embeddings, transcription, and speech synthesis.
The package owns the contracts only: it never chooses a provider, performs network I/O, loads a model, runs inference, authorizes access, or exposes a remote protocol. Provider adapters (local res/int/model and remote HTTP services) satisfy these interfaces. Concrete adapters live in adapters/<name> or in platform implementations of res/int/model.
Zero values are safe where practical. Accept interfaces and return concrete values. All operations accept context.Context.
Contract: inference.provider/v1 (recorded in docs/contract-names.md).
Package inference defines capability interfaces. A provider implements only the interfaces for the operations it supports and advertises them in ProviderInfo.Capabilities. The full Provider bundles Info and Close; every operation is optional.
Package inference speech types define speech-synthesis requests and the bounded byte stream of synthesized audio.
Package inference transcription types define transcription requests and responses. Timestamps carry per-segment or per-word timing.
Index ¶
- Constants
- Variables
- func Category(code string) error
- func CosineSimilarity(a, b []float64) (float64, error)
- func DecodeStructuredOutput[T any](response GenerationResponse, schema json.RawMessage, validate SchemaValidator) (T, error)
- func NormalizeVector(vector []float64) ([]float64, error)
- func ValidateStructuredOutput(response GenerationResponse, schema json.RawMessage, validate SchemaValidator) error
- type Capability
- type Device
- type Embedder
- type Embedding
- type EmbeddingRequest
- type EmbeddingResponse
- type EventSink
- type FinishReason
- type GenerationEvent
- type GenerationRequest
- type GenerationResponse
- type Generator
- type Limits
- type MediaReference
- type Message
- type Modality
- type ModelCatalog
- type ModelInfo
- type ModelLister
- type Part
- type PartKind
- type Provider
- type ProviderInfo
- type RemoteError
- type RetryAfter
- type Role
- type SchemaValidator
- type SinkFunc
- type SpeechRequest
- type SpeechStream
- type Stability
- type Streamer
- type Synthesizer
- type TokenUsage
- type ToolCall
- type ToolDefinition
- type Transcriber
- type TranscriptionRequest
- type TranscriptionResponse
- type TranscriptionSegment
- type TranscriptionWord
Constants ¶
const ( EventKindStarted = "started" EventKindTextDelta = "text.delta" EventKindReasoningDelta = "reasoning.delta" EventKindRefusalDelta = "refusal.delta" EventKindToolDelta = "tool.delta" EventKindToolCompleted = "tool.completed" EventKindUsage = "usage" EventKindCompleted = "completed" EventKindError = "error" )
StreamingEventKinds are the recognized streaming event kinds.
Variables ¶
var ( // ErrAuthentication reports missing or invalid credentials. ErrAuthentication = errors.New("authentication required") // ErrAuthorization reports valid credentials that lack permission. ErrAuthorization = errors.New("authorization failed") // ErrRateLimit reports that the provider is rate limiting the caller. ErrRateLimit = errors.New("rate limited") // ErrTimeout reports that an operation exceeded its deadline. ErrTimeout = errors.New("operation timed out") // ErrCanceled reports that an operation was canceled. ErrCanceled = errors.New("operation canceled") ErrUnavailable = errors.New("provider unavailable") // ErrUnsupported reports an operation or modality the provider does not support. ErrUnsupported = errors.New("operation or modality not supported") // ErrInvalidRequest reports a malformed request. ErrInvalidRequest = errors.New("invalid request") // ErrInvalidResponse reports a malformed provider response. ErrInvalidResponse = errors.New("invalid provider response") // ErrResourceExhausted reports resource exhaustion (memory, tokens, bytes). ErrResourceExhausted = errors.New("resource exhausted") // ErrIncompatibleModel reports that the model cannot serve the request. ErrIncompatibleModel = errors.New("incompatible model") // ErrTransientNative reports a transient native runtime failure. ErrTransientNative = errors.New("transient native failure") )
Functions ¶
func Category ¶
Category maps a string error code to its sentinel error. Unknown codes return ErrInvalidResponse.
func CosineSimilarity ¶
CosineSimilarity compares two finite vectors with equal dimensions.
func DecodeStructuredOutput ¶
func DecodeStructuredOutput[T any](response GenerationResponse, schema json.RawMessage, validate SchemaValidator) (T, error)
func NormalizeVector ¶
NormalizeVector returns a new unit vector without mutating the input.
func ValidateStructuredOutput ¶
func ValidateStructuredOutput(response GenerationResponse, schema json.RawMessage, validate SchemaValidator) error
ValidateStructuredOutput checks that a completed response is a schema-valid JSON object. Refusals, truncation, and tool proposals are never objects.
Types ¶
type Capability ¶
type Capability string
Capability is one operation a provider may advertise.
const ( // CapabilityGenerate performs non-streaming generation. CapabilityGenerate Capability = "generate" // CapabilityStream performs streaming generation. CapabilityStream Capability = "stream" // CapabilityEmbed performs embeddings. CapabilityEmbed Capability = "embed" // CapabilityTranscribe performs transcription. CapabilityTranscribe Capability = "transcribe" // CapabilitySynthesize performs speech synthesis. CapabilitySynthesize Capability = "synthesize" // CapabilityStructuredOutput supports JSON Schema structured output. CapabilityStructuredOutput Capability = "structuredOutput" // CapabilityToolProposal supports tool-call proposals. CapabilityToolProposal Capability = "toolProposal" // CapabilityModelListing supports listing available models. CapabilityModelListing Capability = "modelListing" )
func (Capability) Valid ¶
func (c Capability) Valid() bool
Valid reports whether c is a known capability.
type Embedder ¶
type Embedder interface {
// Embed returns embeddings for the inputs.
Embed(context.Context, EmbeddingRequest) (EmbeddingResponse, error)
}
Embedder performs embeddings.
type Embedding ¶
type Embedding struct {
// Index is the input position.
Index int `json:"index"`
// Vector is the embedding values.
Vector []float64 `json:"vector"`
}
Embedding is one embedding vector.
type EmbeddingRequest ¶
type EmbeddingRequest struct {
// Model is the selected embedding model.
Model string `json:"model"`
// Inputs are the texts to embed. A request has Inputs or TokenInputs, not both.
Inputs []string `json:"inputs,omitempty"`
// TokenInputs are inputs already tokenized for the model, one token-ID array per input,
// for providers that accept them (OpenAI does).
TokenInputs [][]int64 `json:"tokenInputs,omitempty"`
// Options are provider-owned options.
Options json.RawMessage `json:"options,omitempty"`
// Limits are explicit bounds for this request.
Limits Limits `json:"limits,omitempty"`
}
EmbeddingRequest requests embeddings for one or more inputs.
func (EmbeddingRequest) InputCount ¶ added in v0.2.0
func (r EmbeddingRequest) InputCount() int
InputCount is the number of inputs, texts or token arrays, the request embeds.
func (EmbeddingRequest) Validate ¶
func (r EmbeddingRequest) Validate() error
Validate checks the request.
type EmbeddingResponse ¶
type EmbeddingResponse struct {
// Model is the model that served the request.
Model string `json:"model"`
// Embeddings are the per-input vectors, in input order.
Embeddings []Embedding `json:"embeddings"`
// Usage is token accounting.
Usage TokenUsage `json:"usage"`
}
EmbeddingResponse is the result of an embedding call.
func EmbedBatch ¶
func EmbedBatch(ctx context.Context, provider Embedder, requests []EmbeddingRequest, concurrency int) ([]EmbeddingResponse, error)
EmbedBatch performs exactly the caller-supplied requests in input order. Failure cancels outstanding work; it never retries or selects another model.
func (EmbeddingResponse) Validate ¶
func (r EmbeddingResponse) Validate() error
Validate checks the response.
type EventSink ¶
type EventSink interface {
// Emit receives one event. Returning an error terminates the stream.
Emit(ctx context.Context, event GenerationEvent) error
}
EventSink receives streaming events. An emit error stops the request and provides backpressure and cancellation without a background loop.
type FinishReason ¶
type FinishReason string
FinishReason is why generation ended.
const ( // FinishReasonStop means the model reached a natural stopping point. FinishReasonStop FinishReason = "stop" // FinishReasonLength means output hit a token or byte limit. FinishReasonLength FinishReason = "length" // FinishReasonToolCalls means the model proposed tool calls. FinishReasonToolCalls FinishReason = "toolCalls" // FinishReasonContentFilter means output was filtered. FinishReasonContentFilter FinishReason = "contentFilter" // FinishReasonRefusal means the model refused. FinishReasonRefusal FinishReason = "refusal" // FinishReasonPaused means the provider paused a long turn (for example Anthropic's // pause_turn while it runs server tools); sending the response back as the next // assistant message lets it continue. FinishReasonPaused FinishReason = "paused" // FinishReasonOther means the provider ended for a reason none of the others name (for // example Gemini's OTHER); GenerationResponse.ProviderStopReason says which. FinishReasonOther FinishReason = "other" )
func (FinishReason) Valid ¶
func (f FinishReason) Valid() bool
Valid reports whether f is a known finish reason.
type GenerationEvent ¶
type GenerationEvent struct {
// Kind is the event kind.
Kind string `json:"kind"`
// Text is a text delta.
Text string `json:"text,omitempty"`
// Index is the part index for deltas.
Index int `json:"index,omitempty"`
// CallID links tool deltas to a call.
CallID string `json:"callId,omitempty"`
// ToolName names the tool being proposed.
ToolName string `json:"toolName,omitempty"`
// ArgumentsDelta is a partial tool-argument delta.
ArgumentsDelta string `json:"argumentsDelta,omitempty"`
// Response is the final response on completed events.
Response *GenerationResponse `json:"response,omitempty"`
// Call is a completed tool-call proposal.
Call *ToolCall `json:"call,omitempty"`
// Usage is incremental token usage.
Usage *TokenUsage `json:"usage,omitempty"`
}
GenerationEvent is one streaming event.
type GenerationRequest ¶
type GenerationRequest struct {
// Model is the selected model identity.
Model string `json:"model"`
// Messages are the conversation.
Messages []Message `json:"messages"`
// Tools are offered tool definitions.
Tools []ToolDefinition `json:"tools,omitempty"`
// MaxOutputTokens bounds generated output tokens.
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
// Temperature is the sampling temperature, where supported.
Temperature *float64 `json:"temperature,omitempty"`
// OutputSchema is a JSON Schema for structured object output.
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
// Options are provider-owned options with a restricted vocabulary.
Options json.RawMessage `json:"options,omitempty"`
// Limits are explicit bounds for this request.
Limits Limits `json:"limits,omitempty"`
}
GenerationRequest is a request to generate content.
func (GenerationRequest) Validate ¶
func (r GenerationRequest) Validate() error
Validate checks the neutral contract. Provider adapters enforce their own modality, option, and model restrictions explicitly.
type GenerationResponse ¶
type GenerationResponse struct {
// ID is the provider-assigned response ID.
ID string `json:"id,omitempty"`
// Model is the model that served the request.
Model string `json:"model"`
// Message is the assistant message.
Message Message `json:"message"`
// StopReason is why generation ended.
StopReason FinishReason `json:"stopReason,omitempty"`
// ProviderStopReason is the provider's own name for why generation ended, as it sent it.
// It is required when StopReason is FinishReasonOther and optional otherwise.
ProviderStopReason string `json:"providerStopReason,omitempty"`
// Usage is token accounting.
Usage TokenUsage `json:"usage"`
// ProviderMetadata is opaque provider metadata, free of credentials.
ProviderMetadata json.RawMessage `json:"providerMetadata,omitempty"`
// ReasoningContext is opaque reasoning context. It may only be returned to
// its originating provider/model and must never be echoed elsewhere.
ReasoningContext json.RawMessage `json:"reasoningContext,omitempty"`
}
GenerationResponse is the result of a generation call.
func (GenerationResponse) HasToolCalls ¶
func (r GenerationResponse) HasToolCalls() bool
HasToolCalls reports whether the response proposes tool calls.
func (GenerationResponse) IsRefusal ¶
func (r GenerationResponse) IsRefusal() bool
IsRefusal reports whether the response is a refusal.
func (GenerationResponse) Text ¶
func (r GenerationResponse) Text() string
Text returns only text parts.
func (GenerationResponse) Validate ¶
func (r GenerationResponse) Validate() error
Validate checks a response shape.
type Generator ¶
type Generator interface {
// Generate runs one generation pass and returns the complete response.
Generate(context.Context, GenerationRequest) (GenerationResponse, error)
}
Generator performs non-streaming generation.
type Limits ¶
type Limits struct {
// MaxOutputTokens bounds generated output tokens. Zero means unset.
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
// MaxInputTokens bounds input tokens. Zero means unset.
MaxInputTokens int `json:"maxInputTokens,omitempty"`
// MaxBytes bounds the encoded request or response body. Zero means unset.
MaxBytes int64 `json:"maxBytes,omitempty"`
}
Limits are explicit output and input bounds for a request.
type MediaReference ¶
type MediaReference struct {
// Kind is "url" or "file".
Kind string `json:"kind"`
// URI is the reference. For "url" it must use HTTPS with no user or fragment.
URI string `json:"uri"`
}
MediaReference is passed to the selected adapter. Libraries never download URLs or upload local files implicitly. Provider file IDs are opaque.
func (MediaReference) Validate ¶
func (r MediaReference) Validate() error
Validate checks a media reference.
type Message ¶
type Message struct {
// Role is the sender.
Role Role `json:"role"`
// Parts are the message content.
Parts []Part `json:"parts,omitempty"`
// ToolCalls are proposed calls (assistant messages only).
ToolCalls []ToolCall `json:"toolCalls,omitempty"`
// ToolCallID links a tool-result message to its call.
ToolCallID string `json:"toolCallId,omitempty"`
// ToolName names the tool producing the result.
ToolName string `json:"toolName,omitempty"`
// ToolError marks a tool result as failed.
ToolError bool `json:"toolError,omitempty"`
}
Message is one multimodal message in a conversation.
func (Message) PartsHasKind ¶
PartsHasKind reports whether the message has a part of the given kind.
type Modality ¶
type Modality string
Modality is one kind of input or output content.
const ( // ModalityText is plain text. ModalityText Modality = "text" // ModalityImage is an image. ModalityImage Modality = "image" // ModalityAudio is audio. ModalityAudio Modality = "audio" // ModalityVideo is video. ModalityVideo Modality = "video" // ModalityFile is a file or explicitly approved reference. ModalityFile Modality = "file" )
type ModelCatalog ¶
type ModelCatalog struct {
// contains filtered or unexported fields
}
ModelCatalog records explicit caller-supplied model bindings. It performs no discovery, endpoint selection, fallback, credential lookup, or retries.
func (*ModelCatalog) Models ¶
func (c *ModelCatalog) Models() []ModelInfo
type ModelInfo ¶
type ModelInfo struct {
// ID is the model identity used in requests.
ID string `json:"id"`
// Name is a human-readable name.
Name string `json:"name,omitempty"`
// Provider is the provider that serves the model.
Provider string `json:"provider,omitempty"`
// Capabilities are the operations the model supports.
Capabilities []Capability `json:"capabilities,omitempty"`
// Modalities are the input/output kinds the model supports.
Modalities []Modality `json:"modalities,omitempty"`
// Devices are the compute devices the model can use.
Devices []Device `json:"devices,omitempty"`
// Stability is the maturity of the model.
Stability Stability `json:"stability,omitempty"`
}
ModelInfo describes one model a provider can serve.
func (ModelInfo) HasCapability ¶
func (m ModelInfo) HasCapability(c Capability) bool
HasCapability reports whether the model advertises the capability.
type ModelLister ¶
type ModelLister interface {
// ListModels returns the models the provider can serve.
ListModels(context.Context) ([]ModelInfo, error)
}
ModelLister lists available models, where supported.
type Part ¶
type Part struct {
// Kind is the part kind.
Kind PartKind `json:"kind"`
// Text is the text content for text/reasoning/refusal parts.
Text string `json:"text,omitempty"`
// MediaType is the MIME type for binary parts.
MediaType string `json:"mediaType,omitempty"`
// Data is the inline binary content. Binary parts use either Data or Reference.
Data []byte `json:"data,omitempty"`
// Reference is an approved file or URL reference.
Reference *MediaReference `json:"reference,omitempty"`
// ProviderData is opaque provider context, passed back only to its origin.
ProviderData json.RawMessage `json:"providerData,omitempty"`
}
Part is one item of multimodal content. Exactly one of Data or Reference is set for binary parts; ProviderData is opaque context echoed only to its originating provider/model.
type PartKind ¶
type PartKind string
PartKind is one kind of message content.
const ( // PartKindText is ordinary text content. PartKindText PartKind = "text" // PartKindReasoning is opaque model reasoning, returned only to its origin. PartKindReasoning PartKind = "reasoning" // PartKindRefusal is a refusal to comply. PartKindRefusal PartKind = "refusal" // PartKindImage is an image part. PartKindImage PartKind = "image" // PartKindAudio is an audio part. PartKindAudio PartKind = "audio" // PartKindVideo is a video part. PartKindVideo PartKind = "video" // PartKindFile is a file part or approved reference. PartKindFile PartKind = "file" // PartKindContext is opaque provider context echoed back to its origin. PartKindContext PartKind = "context" )
type Provider ¶
type Provider interface {
// Info returns protocol metadata about the provider. It must not expose
// credentials.
Info(context.Context) (ProviderInfo, error)
// Close releases the provider and any sessions it owns. It is safe to call
// after an error and is idempotent.
Close() error
}
Provider is the base interface every inference provider implements. It reports identity and metadata and releases resources. Every operation is provided by a separate capability interface.
type ProviderInfo ¶
type ProviderInfo struct {
// ID is the stable provider identity (for example "openai", "coreml").
ID string `json:"id"`
// Name is a human-readable display name.
Name string `json:"name,omitempty"`
// Version is the provider implementation version.
Version string `json:"version,omitempty"`
// Stability is the maturity of the provider.
Stability Stability `json:"stability,omitempty"`
// Modalities are the input/output kinds the provider supports.
Modalities []Modality `json:"modalities,omitempty"`
// Capabilities are the operations the provider supports.
Capabilities []Capability `json:"capabilities,omitempty"`
// Devices are the compute devices the provider reports, where relevant.
Devices []Device `json:"devices,omitempty"`
// Limits are the provider's default bounds. A request may tighten them.
Limits Limits `json:"limits,omitempty"`
// Protocol is protocol metadata that does not expose credentials.
Protocol map[string]string `json:"protocol,omitempty"`
}
ProviderInfo is protocol metadata about a provider. It must not expose credentials or secrets.
func (ProviderInfo) HasCapability ¶
func (p ProviderInfo) HasCapability(c Capability) bool
HasCapability reports whether the provider advertises the capability.
func (ProviderInfo) HasDevice ¶
func (p ProviderInfo) HasDevice(d Device) bool
HasDevice reports whether the provider reports the device.
func (ProviderInfo) HasModality ¶
func (p ProviderInfo) HasModality(m Modality) bool
HasModality reports whether the provider supports the modality.
func (ProviderInfo) Supports ¶
func (p ProviderInfo) Supports(cap Capability) bool
Supports reports whether the provider can perform the operation for the request. Operations map to capabilities: Generate→CapabilityGenerate, Stream→CapabilityStream, Embed→CapabilityEmbed, Transcribe→CapabilityTranscribe, Synthesize→CapabilitySynthesize.
func (ProviderInfo) Validate ¶
func (p ProviderInfo) Validate() error
Validate checks provider identity and declared values.
type RemoteError ¶
type RemoteError struct {
// Code is the error category as a string (for example "authentication",
// "rateLimit", "unavailable"). Use Category to obtain the sentinel error.
Code string `json:"code"`
// Message is a human-readable summary, bounded and free of credentials.
Message string `json:"message,omitempty"`
// RetryAfter is the suggested wait before retrying.
RetryAfter RetryAfter `json:"retryAfter,omitempty"`
// Provider is the provider that originated the error.
Provider string `json:"provider,omitempty"`
}
RemoteError is a structured error returned by a provider. It carries a stable code (a string category), a bounded message, and optional retry-after information. Code maps to one of the Err* sentinel errors via Category.
func NewRemoteError ¶
func NewRemoteError(code error, message string, provider string) *RemoteError
NewRemoteError builds a RemoteError from a category sentinel. Message is truncated to 4096 bytes on a character boundary.
func (*RemoteError) Error ¶
func (e *RemoteError) Error() string
func (*RemoteError) Is ¶
func (e *RemoteError) Is(target error) bool
Is reports whether the remote error matches a category sentinel.
func (*RemoteError) Unwrap ¶
func (e *RemoteError) Unwrap() error
Unwrap supports errors.Is by mapping the string code to a sentinel error.
type RetryAfter ¶
type RetryAfter struct {
// Delay is the suggested wait before retrying. Zero means unset.
Delay time.Duration `json:"delay,omitempty"`
// Source describes where the delay came from (for example "header").
// It must not contain credentials.
Source string `json:"source,omitempty"`
}
RetryAfter carries bounded retry-after information. Zero means unset.
func (RetryAfter) IsZero ¶
func (r RetryAfter) IsZero() bool
IsZero reports whether the retry-after is unset.
type SchemaValidator ¶
type SchemaValidator func(schema, value json.RawMessage) error
SchemaValidator checks one JSON value against a caller-supplied JSON Schema. Injection keeps the portable inference module independent of a particular schema engine while requiring real validation before typed decoding.
type SinkFunc ¶
type SinkFunc func(context.Context, GenerationEvent) error
SinkFunc adapts a function to EventSink.
type SpeechRequest ¶
type SpeechRequest struct {
// Model is the selected synthesis model.
Model string `json:"model"`
// Input is the text to synthesize.
Input string `json:"input"`
// Voice is the voice identifier, where supported.
Voice string `json:"voice,omitempty"`
// Format is the output audio format (for example "mp3", "wav", "opus").
Format string `json:"format,omitempty"`
// Options are provider-owned options.
Options json.RawMessage `json:"options,omitempty"`
// Limits are explicit bounds for this request.
Limits Limits `json:"limits,omitempty"`
}
SpeechRequest requests speech synthesis of text.
func (SpeechRequest) Validate ¶
func (r SpeechRequest) Validate() error
Validate checks the request.
type SpeechStream ¶
type SpeechStream interface {
// Read reads up to len(p) audio bytes. It returns io.EOF when the stream
// is complete. Cancellation or an error aborts the stream.
Read(p []byte) (int, error)
// Close releases the stream. It is safe to call after an error and is
// idempotent.
Close() error
}
SpeechStream is a bounded stream of synthesized audio bytes. Close releases the stream and any underlying audio resources.
type Stability ¶
type Stability string
Stability reports the maturity of a provider or a declared capability.
const ( // StabilityExperimental is a new capability whose contract may change. StabilityExperimental Stability = "experimental" // StabilityStable is a supported capability with a frozen contract. StabilityStable Stability = "stable" // StabilityLegacy is still supported but superseded. StabilityLegacy Stability = "legacy" // StabilityDeprecated is scheduled for removal. StabilityDeprecated Stability = "deprecated" )
type Streamer ¶
type Streamer interface {
// Stream streams generation events to sink and returns the final response.
Stream(context.Context, GenerationRequest, EventSink) (GenerationResponse, error)
}
Streamer performs streaming generation through an EventSink. The sink's emit error provides backpressure and cancellation.
type Synthesizer ¶
type Synthesizer interface {
// Synthesize synthesizes text to audio.
Synthesize(context.Context, SpeechRequest) (SpeechStream, error)
}
Synthesizer performs speech synthesis, returning a bounded byte stream.
type TokenUsage ¶
type TokenUsage struct {
Input int64 `json:"input"`
Output int64 `json:"output"`
Total int64 `json:"total"`
CachedInput int64 `json:"cachedInput,omitempty"`
Reasoning int64 `json:"reasoning,omitempty"`
}
TokenUsage reports token accounting.
type ToolCall ¶
type ToolCall struct {
// ID is the unique call identifier.
ID string `json:"id"`
// Name is the tool name.
Name string `json:"name"`
// Arguments are the tool arguments as a JSON object.
Arguments json.RawMessage `json:"arguments"`
// ProviderData is opaque provider context.
ProviderData json.RawMessage `json:"providerData,omitempty"`
}
ToolCall is one proposed tool call. The host never executes tools automatically; it presents the proposal to the caller.
type ToolDefinition ¶
type ToolDefinition struct {
// Name is the tool name.
Name string `json:"name"`
// Description documents the tool.
Description string `json:"description,omitempty"`
// InputSchema is a JSON Schema object for the tool arguments.
InputSchema json.RawMessage `json:"inputSchema"`
}
ToolDefinition is one tool the caller offers. InputSchema is a JSON Schema object describing accepted arguments.
func (ToolDefinition) Validate ¶
func (t ToolDefinition) Validate() error
Validate checks a tool definition.
type Transcriber ¶
type Transcriber interface {
// Transcribe transcribes audio.
Transcribe(context.Context, TranscriptionRequest) (TranscriptionResponse, error)
}
Transcriber performs transcription.
type TranscriptionRequest ¶
type TranscriptionRequest struct {
// Model is the selected transcription model.
Model string `json:"model"`
// Audio is the audio bytes to transcribe.
Audio []byte `json:"audio,omitempty"`
// MediaType is the MIME type of the audio (must be audio/*).
MediaType string `json:"mediaType,omitempty"`
// Prompt is an optional transcription prompt.
Prompt string `json:"prompt,omitempty"`
// Language is the language code, where supported.
Language string `json:"language,omitempty"`
// Timestamps selects "word" and/or "segment" timing.
Timestamps []string `json:"timestamps,omitempty"`
// Options are provider-owned options.
Options json.RawMessage `json:"options,omitempty"`
// Limits are explicit bounds for this request.
Limits Limits `json:"limits,omitempty"`
}
TranscriptionRequest requests transcription of audio.
func (TranscriptionRequest) Validate ¶
func (r TranscriptionRequest) Validate() error
Validate checks the request.
type TranscriptionResponse ¶
type TranscriptionResponse struct {
// Text is the full transcription.
Text string `json:"text"`
// Language is the detected or requested language.
Language string `json:"language,omitempty"`
// DurationSeconds is the audio duration in seconds.
DurationSeconds *float64 `json:"durationSeconds,omitempty"`
// Segments are per-segment transcriptions.
Segments []TranscriptionSegment `json:"segments,omitempty"`
// Words are per-word transcriptions.
Words []TranscriptionWord `json:"words,omitempty"`
}
TranscriptionResponse is the result of a transcription call.
func (TranscriptionResponse) Validate ¶
func (r TranscriptionResponse) Validate() error
Validate checks the response.
type TranscriptionSegment ¶
type TranscriptionSegment struct {
// ID is the segment index.
ID int `json:"id"`
// Text is the transcribed text.
Text string `json:"text"`
// Start is the start time in seconds.
Start float64 `json:"start"`
// End is the end time in seconds.
End float64 `json:"end"`
}
TranscriptionSegment is one transcribed segment with timing in seconds.
type TranscriptionWord ¶
type TranscriptionWord struct {
// Word is the transcribed word.
Word string `json:"word"`
// Start is the start time in seconds.
Start float64 `json:"start"`
// End is the end time in seconds.
End float64 `json:"end"`
}
TranscriptionWord is one transcribed word with timing in seconds.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package mladapter adapts res/int/model (low-level tensor inference) into res/int/inference (high-level generation, embeddings, transcription, synthesis).
|
Package mladapter adapts res/int/model (low-level tensor inference) into res/int/inference (high-level generation, embeddings, transcription, synthesis). |