Documentation
¶
Overview ¶
Package base defines the unified provider abstraction shared across all PromptKit provider types (inference, TTS, STT, embedding, image generation).
Every provider implements Provider for cross-cutting concerns (identity, pricing, lifecycle) and exactly one of the per-type interfaces below for capability-specific operations.
Package base — canonical token-unit vocabulary shared by all inference providers and their pricing tables. The pricing engine still accepts any unit string; these constants exist so providers and price items never drift.
Index ¶
- Constants
- Variables
- func APIKeyFromCredential(c credentials.Credential) string
- func AggregateCost(parts ...*types.CostInfo) types.CostInfo
- func ApplyHTTPTuning(provider any, providerType string, t HTTPTuning) error
- func ApplyRateLimit(c *http.Client, limiter *rate.Limiter)
- func AzureAPIVersion(pc *credentials.PlatformConfig) string
- func AzureHTTPClient(cred credentials.Credential, pc *credentials.PlatformConfig, ...) *http.Client
- func ClientTimeout(c *http.Client) time.Duration
- func ClientTransport(c *http.Client) http.RoundTripper
- func ContextWindowFromConfig(additional map[string]any) int
- func CostInfoToMetaMap(ci *types.CostInfo) map[string]any
- func CredentialRedirectPolicy(names func() []string, next func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error
- func GetTyped[T Provider](r *Registry, name string, typ ProviderType) (T, error)
- func MakeCostInfo(desc *PricingDescriptor, providerName string, capability ProviderType, ...) *types.CostInfo
- func NewHTTPService(apiKey string, defaults HTTPServiceDefaults, opts ...HTTPServiceOption) (*Implementation, *HTTPServiceFields)
- func NewHeaderTransport(next http.RoundTripper, headers map[string]string) http.RoundTripper
- func NewRequestLimiter(requestsPerSecond float64, burst int) *rate.Limiter
- func PriceUsage(desc *PricingDescriptor, providerName string, capability ProviderType, ...) types.CostInfo
- func ReadAllAudio(stream TTSStream) ([]byte, *types.CostInfo, error)
- func ResolveContextWindow(providerID, model string, override int, table map[string]int) int
- func ResolveCredential(ctx context.Context, providerType string, cfgDir string, ...) (credentials.Credential, error)
- func SameOriginAsFirstHop(req *http.Request) bool
- func StartCapabilitySpan(ctx context.Context, tracer trace.Tracer, args *SpanArgs) (context.Context, trace.Span)
- func WarnPlatformIgnored(id, providerType, platform string)
- func WithCredentialRedirectPolicy(c *http.Client) *http.Client
- type CapabilitySpec
- type CredentialTransport
- type EmbeddingProvider
- type EmbeddingRequest
- type EmbeddingResponse
- type Factory
- type FactoryRegistry
- func (r *FactoryRegistry[T]) Create(spec CapabilitySpec) (T, error)
- func (r *FactoryRegistry[T]) Register(implType string, f Factory[T])
- func (r *FactoryRegistry[T]) RegisterPlatforms(implType string, platforms ...string)
- func (r *FactoryRegistry[T]) ResolveCredential(ctx context.Context, implType string, cfgDir string, ...) (credentials.Credential, error)
- func (r *FactoryRegistry[T]) SupportsPlatform(implType, platform string) bool
- func (r *FactoryRegistry[T]) Types() []string
- type FlatPricing
- type HTTPServiceDefaults
- type HTTPServiceFields
- type HTTPServiceOption
- func AzureOpenAIServiceOptions(spec *CapabilitySpec, timeout time.Duration) ([]HTTPServiceOption, error)
- func OpenAIWireAuth(spec *CapabilitySpec, timeout time.Duration) ([]HTTPServiceOption, string, error)
- func WithAPIKey(k string) HTTPServiceOption
- func WithBaseURL(url string) HTTPServiceOption
- func WithClient(c *http.Client) HTTPServiceOption
- func WithModel(m string) HTTPServiceOption
- type HTTPTunable
- type HTTPTuning
- type ImageProvider
- type ImageRequest
- type ImageResponse
- type Implementation
- func (i *Implementation) Close() error
- func (i *Implementation) HealthCheck(ctx context.Context) error
- func (i *Implementation) Init(ctx context.Context) error
- func (i *Implementation) MessageMetadataTemplate() string
- func (i *Implementation) Name() string
- func (i *Implementation) Pricing() *PricingDescriptor
- func (i *Implementation) SetMessageMetadataTemplate(t string)
- func (i *Implementation) SetPricing(p *PricingDescriptor)
- func (i *Implementation) Type() ProviderType
- func (i *Implementation) Validate() error
- type InferenceProvider
- type InlinePricingResolver
- type LineItem
- type PriceItem
- type PricingDescriptor
- type PricingRef
- type PricingResolver
- type PricingSource
- type Provider
- type ProviderType
- type RateLimitTransport
- type Registry
- func (r *Registry) CloseAll() error
- func (r *Registry) Get(name string, typ ProviderType) (Provider, error)
- func (r *Registry) GetAll(typ ProviderType) []Provider
- func (r *Registry) InitAll(ctx context.Context) error
- func (r *Registry) PricingResolver() PricingResolver
- func (r *Registry) Register(p Provider) error
- func (r *Registry) Replace(p Provider) error
- func (r *Registry) SetPricingResolver(res PricingResolver)
- func (r *Registry) Unregister(name string, typ ProviderType) bool
- type STTProvider
- type STTRequest
- type STTResponse
- type SpanArgs
- type TTSProvider
- type TTSRequest
- type TTSStream
- type TokenUsage
- type TokenWaiter
- type VideoProvider
- type VideoRequest
- type VideoResponse
Constants ¶
const ( UnitInputToken = "input_token" // full-price, uncached input UnitCacheReadToken = "cache_read_token" // prompt-cache read (discounted input) UnitCacheWriteToken = "cache_write_token" //nolint:gosec // prompt-cache creation (premium input), not a credential UnitOutputToken = "output_token" // visible output only, EXCLUDES reasoning UnitReasoningToken = "reasoning_token" // thinking tokens, priced additively UnitAudioInputToken = "audio_input_token" //nolint:gosec // realtime audio in, not a credential UnitAudioOutputToken = "audio_output_token" // realtime audio out UnitImageInputToken = "image_input_token" // image input, where a model prices it apart from text UnitVideoInputToken = "video_input_token" // video input, where a model prices it apart from text UnitImageOutputToken = "image_output_token" // generated images, billed per token )
Canonical token units. Providers MUST emit these names; pricing tables MUST price them by the same names.
const ContextWindowConfigKey = "context_window"
ContextWindowConfigKey is the provider spec additional_config key that sets a model's context window in tokens, overriding the built-in table. It is how a self-hosted model (vLLM, Ollama) or a model newer than the table declares its window.
const PlatformAzure = "azure"
PlatformAzure is the PlatformConfig.Type of an Azure-hosted provider.
Variables ¶
var ErrRateLimitPastDeadline = errors.New("provider rate limit: the next request slot is past the context deadline")
ErrRateLimitPastDeadline reports that a request's turn under the provider's rate limit comes after its context deadline, so the request was not sent. It wraps context.DeadlineExceeded, so retry loops treat it as a deadline and do not retry it.
var ErrRequestAuthorization = errors.New("provider credential could not be applied")
ErrRequestAuthorization wraps an error from RateLimitTransport.Authorize: the request's credential could not be applied, so it was not sent. Retry loops do not retry it, and providers do not class it as transient: a credential that cannot be fetched or signed is not an infrastructure blip.
var WellKnownCredentialHeaders = httputil.WellKnownCredentialHeaders
WellKnownCredentialHeaders is httputil.WellKnownCredentialHeaders: the headers CredentialRedirectPolicy always drops off the origin.
Functions ¶
func APIKeyFromCredential ¶
func APIKeyFromCredential(c credentials.Credential) string
APIKeyFromCredential returns the raw API key from an APIKey credential, or "" for any other credential shape (or nil).
func AggregateCost ¶
AggregateCost merges per-message CostInfo into one roll-up: it sums Quantities, merges Breakdown line items by (provider, capability, unit, dimensions), and re-derives the flat directional headlines so the TotalCost == Input+Output+Cached invariant holds on the aggregate. This is the single source of truth for cost roll-up — no caller sums CostInfo by hand.
A part with an empty Breakdown (headline-only: pre-migration provider results, or older/serialized CostInfo values that never populated Breakdown/Quantities) is never dropped — its flat fields are synthesized into breakdown lines so the cost flows through the same merge path. A part with a non-empty Breakdown uses only that Breakdown (its flat fields are re-derived output, not re-read) to avoid double-counting.
func ApplyHTTPTuning ¶ added in v2.12.0
func ApplyHTTPTuning(provider any, providerType string, t HTTPTuning) error
ApplyHTTPTuning applies t to the provider built for providerType. A zero t is a no-op for any provider; a non-zero t is an error for a provider that is not HTTPTunable, so a declared setting is never silently dropped.
func ApplyRateLimit ¶ added in v2.17.0
ApplyRateLimit puts limiter in front of c's transport, replacing any limit c already has, so applying a new one never stacks two. c's Timeout moves onto the RateLimitTransport so the wait does not use it up. A nil limiter removes the limit and gives the timeout back to c. A nil c is a no-op.
func AzureAPIVersion ¶ added in v2.21.0
func AzureAPIVersion(pc *credentials.PlatformConfig) string
AzureAPIVersion returns the platform's additional_config.api_version, or credentials.DefaultAzureAPIVersion when it sets none.
func AzureHTTPClient ¶ added in v2.21.0
func AzureHTTPClient(cred credentials.Credential, pc *credentials.PlatformConfig, timeout time.Duration) *http.Client
AzureHTTPClient returns a client that authenticates every request with cred and adds the platform's api-version, for a service hosted on Azure.
func ClientTimeout ¶ added in v2.17.0
ClientTimeout returns c's effective request timeout: c.Timeout, or the Timeout ApplyRateLimit moved onto its RateLimitTransport. Nil c returns 0.
func ClientTransport ¶ added in v2.17.0
func ClientTransport(c *http.Client) http.RoundTripper
ClientTransport returns c's transport beneath any RateLimitTransport. Nil c returns nil.
func ContextWindowFromConfig ¶ added in v2.17.0
ContextWindowFromConfig reads the context_window override from a provider spec's additional_config. It returns 0 when the key is absent or not a positive number (YAML decodes integers as int, JSON as float64).
func CostInfoToMetaMap ¶
CostInfoToMetaMap serializes a CostInfo into the map[string]any shape the arena statestore expects when reading ancillary cost from Message.Meta keys (tts_cost, stt_cost, etc.). The keys and types must match what PromptArena's statestore telemetry costInfoFromMeta reads.
func CredentialRedirectPolicy ¶ added in v2.17.0
func CredentialRedirectPolicy( names func() []string, next func(*http.Request, []*http.Request) error, ) func(*http.Request, []*http.Request) error
CredentialRedirectPolicy is httputil.CredentialRedirectPolicy; see there. The policy lives in httputil so packages that do not otherwise depend on the providers (the a2a client) can use it.
func GetTyped ¶
func GetTyped[T Provider](r *Registry, name string, typ ProviderType) (T, error)
GetTyped is a generic helper that returns a provider as a specific interface type T. Returns an error if the registered provider doesn't satisfy T.
func MakeCostInfo ¶
func MakeCostInfo( desc *PricingDescriptor, providerName string, capability ProviderType, quantities map[string]float64, latency time.Duration, ) *types.CostInfo
MakeCostInfo builds a *types.CostInfo from raw quantities and prices every unit it can match against the supplied descriptor. Returns the CostInfo with quantities and identity tags populated even if pricing is nil — callers can decide whether to drop a nil-cost entry. Any nonzero quantity unit that has no matching price item is NOT silently swallowed to $0: the priced-partial total is kept and the gap is surfaced via a deduped warning (see warnUnpriced), so operators see undercounted cost instead of a false zero. This is the shared cost-construction path for ancillary providers (TTS, STT, image gen) that report a single-quantity unit at call time.
func NewHTTPService ¶
func NewHTTPService( apiKey string, defaults HTTPServiceDefaults, opts ...HTTPServiceOption, ) (*Implementation, *HTTPServiceFields)
NewHTTPService produces the standard *Implementation + *HTTPServiceFields pair every HTTP-backed provider impl embeds, applying any caller-supplied HTTPServiceOption mutations on the way out. Eliminates per-impl constructor boilerplate.
defaults is passed by value to keep call sites composable.
func NewHeaderTransport ¶ added in v2.12.0
func NewHeaderTransport(next http.RoundTripper, headers map[string]string) http.RoundTripper
NewHeaderTransport returns a RoundTripper that adds headers to a clone of every request before delegating to next (http.DefaultTransport when nil). A header already present on the request — set by the provider, or by an auth transport wrapping this one — is not overwritten: the request fails with an error naming it, so a custom header can never silently replace a credential.
func NewRequestLimiter ¶ added in v2.17.0
NewRequestLimiter returns the token bucket for a provider's rate_limit: a sustained requestsPerSecond with room for burst requests at once. A requestsPerSecond of zero or less returns nil, which means unlimited. A burst below 1 is raised to 1, so a rate without a burst spaces requests evenly rather than refusing them all.
func PriceUsage ¶
func PriceUsage( desc *PricingDescriptor, providerName string, capability ProviderType, usage TokenUsage, dims map[string]string, latency time.Duration, ) types.CostInfo
PriceUsage prices a normalized TokenUsage against desc, populating the authoritative Quantities+Breakdown and deriving the flat headline view. A nonzero unit with no price (and a non-nil descriptor) is surfaced loudly (deduped) and contributes to no cost — the total is the priced-partial sum, never a fabricated constant and never a swallowed $0. A nil descriptor is a free/local provider: zero cost, no warning.
func ReadAllAudio ¶
ReadAllAudio drains a TTSStream into a byte slice and returns it along with the total cost. Convenience for callers that need the full audio up front (tests, batch synthesis, mocks).
func ResolveContextWindow ¶ added in v2.17.0
ResolveContextWindow selects a model's context window in tokens, in order: a positive spec override > the provider's built-in table, keyed like the pricing table (a vendor prefix such as "anthropic/" is stripped; there is no substring fallback). It returns 0 when neither knows the model, which tells the caller to use its own default; that case is logged at debug level.
func ResolveCredential ¶
func ResolveCredential( ctx context.Context, providerType string, cfgDir string, cred *credentials.CredentialConfig, ) (credentials.Credential, error)
ResolveCredential resolves a provider's credential block into a concrete Credential. Shared by every typed-provider package's factory layer.
func SameOriginAsFirstHop ¶ added in v2.17.0
SameOriginAsFirstHop is httputil.SameOriginAsFirstHop; see there.
func StartCapabilitySpan ¶
func StartCapabilitySpan(ctx context.Context, tracer trace.Tracer, args *SpanArgs) (context.Context, trace.Span)
StartCapabilitySpan begins a span named "<capability>.<operation>" with the standard provider.* attributes. Callers should defer span.End().
func WarnPlatformIgnored ¶ added in v2.21.0
func WarnPlatformIgnored(id, providerType, platform string)
WarnPlatformIgnored logs that a provider type runs on no platform, so the one its spec names has no effect. Every role shares the message.
Types ¶
type CapabilitySpec ¶
type CapabilitySpec struct {
// ID is a stable identifier; informational only at this layer.
ID string
// Type selects the implementation (e.g. openai, elevenlabs, cartesia).
Type string
// Model overrides the provider's default model.
Model string
// BaseURL overrides the provider's default API endpoint.
BaseURL string
// Credential carries the resolved credential. For a platform-hosted
// provider it is the platform's credential (an Entra token, say).
Credential credentials.Credential
// Platform hosts the provider on a cloud platform (e.g. azure). Nil
// means the provider's own API. A type that does not declare the
// platform (RegisterPlatforms) is built without it, with a warning.
Platform *credentials.PlatformConfig
// AdditionalConfig carries provider-specific extras. Unknown keys
// are ignored.
AdditionalConfig map[string]any
// Tuning carries the provider file's headers, request_timeout and
// http_transport. Create applies it after construction and rejects it
// for an implementation that is not HTTPTunable.
Tuning HTTPTuning
}
CapabilitySpec is the unified runtime form of a typed-provider declaration (TTS, STT, embedding, image gen). The SDK's runtime-config layer translates pkg/config provider configs into this struct after resolving credentials.
Each capability package (tts, stt, embedding, image) aliases this type to preserve back-compat field-naming while sharing the factory machinery.
type CredentialTransport ¶ added in v2.21.0
type CredentialTransport struct {
Base http.RoundTripper
Cred credentials.Credential
APIVersion string // set only for Azure
}
CredentialTransport applies a credential (and, for Azure, the api-version query parameter) to every request before delegating to Base. It is how a platform-hosted provider authenticates: the credential is applied per request, so a token that expires is refreshed by the credential itself.
It implements layeredTransport, so HTTPTuning replaces or wraps only Base and the credential stays the outermost layer.
func (*CredentialTransport) BaseTransport ¶ added in v2.21.0
func (rt *CredentialTransport) BaseTransport() http.RoundTripper
BaseTransport returns the transport the credential-applying layer delegates to.
func (*CredentialTransport) RoundTrip ¶ added in v2.21.0
RoundTrip applies the api-version query param (Azure) and the credential to a cloned request before delegating to the base transport.
func (*CredentialTransport) WithBaseTransport ¶ added in v2.21.0
func (rt *CredentialTransport) WithBaseTransport(next http.RoundTripper) http.RoundTripper
WithBaseTransport returns a copy of rt that delegates to next.
type EmbeddingProvider ¶
type EmbeddingProvider interface {
Provider
Embed(ctx context.Context, req EmbeddingRequest) (EmbeddingResponse, error)
}
EmbeddingProvider returns vectors for input texts.
type EmbeddingRequest ¶
EmbeddingRequest carries text inputs for a vector embedding call.
type EmbeddingResponse ¶
EmbeddingResponse holds the embedding vectors and metadata from a provider.
type Factory ¶
type Factory[T any] func(spec CapabilitySpec) (T, error)
Factory builds a typed Provider from a CapabilitySpec.
type FactoryRegistry ¶
type FactoryRegistry[T any] struct { // contains filtered or unexported fields }
FactoryRegistry is a typed registry keyed by the implementation discriminator (spec.Type). Each capability package owns one registry instance.
func NewFactoryRegistry ¶
func NewFactoryRegistry[T any]() *FactoryRegistry[T]
NewFactoryRegistry creates an empty registry.
func (*FactoryRegistry[T]) Create ¶
func (r *FactoryRegistry[T]) Create(spec CapabilitySpec) (T, error)
Create dispatches to the registered factory for spec.Type, then applies spec.Tuning to the result.
spec is a value-semantics builder; callers assemble inline.
func (*FactoryRegistry[T]) Register ¶
func (r *FactoryRegistry[T]) Register(implType string, f Factory[T])
Register adds a factory under the given implementation type.
func (*FactoryRegistry[T]) RegisterPlatforms ¶ added in v2.21.0
func (r *FactoryRegistry[T]) RegisterPlatforms(implType string, platforms ...string)
RegisterPlatforms declares the hosting platforms implType's factory wires: it receives spec.Platform for them and builds the platform endpoint and credential itself.
func (*FactoryRegistry[T]) ResolveCredential ¶ added in v2.21.0
func (r *FactoryRegistry[T]) ResolveCredential( ctx context.Context, implType string, cfgDir string, cred *credentials.CredentialConfig, platform *credentials.PlatformConfig, ) (credentials.Credential, error)
ResolveCredential resolves the credential a spec of implType is built with. For a platform implType declares, that is the platform's credential chain (an Entra token, say); otherwise the platform is not consulted, so a type that cannot run there still authenticates to its own API, and Create warns that the platform is ignored.
func (*FactoryRegistry[T]) SupportsPlatform ¶ added in v2.21.0
func (r *FactoryRegistry[T]) SupportsPlatform(implType, platform string) bool
SupportsPlatform reports whether implType declared platform.
func (*FactoryRegistry[T]) Types ¶
func (r *FactoryRegistry[T]) Types() []string
Types returns the implementation types with a registered factory, sorted. Callers use it to discover what Create will accept without attempting a construction and string-matching the error — e.g. a deploy adapter validating provider bindings before serving traffic.
type FlatPricing ¶
type FlatPricing struct {
Input float64 // per 1K input tokens
Output float64 // per 1K output tokens
}
FlatPricing is the legacy per-1K input/output rate a config may carry. It is mapped to canonical input_token/output_token price items when no richer descriptor is supplied. base defines its own type (rather than reusing a providers-package type) to avoid importing the providers package, which would create an import cycle.
type HTTPServiceDefaults ¶
type HTTPServiceDefaults struct {
// Name is the provider's unique registry name (e.g. "openai-whisper").
Name string
// Type is the capability discriminator (inference, tts, stt, ...).
Type ProviderType
// Pricing is the compiled-in pricing descriptor.
Pricing *PricingDescriptor
// BaseURL is the default API endpoint.
BaseURL string
// Model is the default model identifier.
Model string
// Timeout is the default HTTP client timeout. Zero is treated as
// http.DefaultClient (no timeout) — pass a positive value.
Timeout time.Duration
}
HTTPServiceDefaults carries the construction-time defaults for an HTTP service provider (TTS, STT impls). Used by NewHTTPService to produce the standard *Implementation + *HTTPServiceFields pair every impl embeds.
type HTTPServiceFields ¶
HTTPServiceFields is the shared HTTP-call configuration embedded by service-style providers (TTS, STT impls). Each impl embeds *HTTPServiceFields to inherit APIKey/BaseURL/Model/Client storage plus the With* option helpers in this package — eliminating per-package With* boilerplate.
func (*HTTPServiceFields) ApplyHTTPTuning ¶ added in v2.12.0
func (f *HTTPServiceFields) ApplyHTTPTuning(t HTTPTuning) error
ApplyHTTPTuning replaces f.Client with a tuned copy. Promoted to every service that embeds *HTTPServiceFields.
type HTTPServiceOption ¶
type HTTPServiceOption func(*HTTPServiceFields)
HTTPServiceOption mutates an HTTPServiceFields. Each impl re-types this for their own option signatures (e.g., type OpenAIOption = HTTPServiceOption).
func AzureOpenAIServiceOptions ¶ added in v2.21.0
func AzureOpenAIServiceOptions(spec *CapabilitySpec, timeout time.Duration) ([]HTTPServiceOption, error)
AzureOpenAIServiceOptions hosts an OpenAI-wire HTTP service (TTS, STT) on the Azure resource spec.Platform names. The deployment is spec.Model; the base URL is its deployment path unless spec.BaseURL overrides it, and the client applies the platform credential and api-version to every request.
func OpenAIWireAuth ¶ added in v2.21.0
func OpenAIWireAuth(spec *CapabilitySpec, timeout time.Duration) ([]HTTPServiceOption, string, error)
OpenAIWireAuth returns how an OpenAI-wire HTTP service (TTS, STT) built from spec authenticates: the static API key, or, for a spec Create left a platform on (azure is the only one these services declare), the options that host it there and no key.
func WithAPIKey ¶
func WithAPIKey(k string) HTTPServiceOption
WithAPIKey sets the API key (rarely used directly; constructors take it as a positional arg, but exposed for completeness).
func WithBaseURL ¶
func WithBaseURL(url string) HTTPServiceOption
WithBaseURL overrides the service's API base URL (testing, proxies).
func WithClient ¶
func WithClient(c *http.Client) HTTPServiceOption
WithClient overrides the HTTP client (custom timeout / transport).
type HTTPTunable ¶ added in v2.12.0
type HTTPTunable interface {
ApplyHTTPTuning(t HTTPTuning) error
}
HTTPTunable is implemented by capability providers that accept HTTPTuning. The capability factories apply a non-zero tuning through it after construction and reject one for a provider that does not implement it.
type HTTPTuning ¶ added in v2.12.0
type HTTPTuning struct {
// Headers are added to every HTTP request the provider makes. A header
// the provider itself sets (its credential, its content type) is not
// overridden: the request fails with an error naming the header instead.
Headers map[string]string
// RequestTimeout replaces the provider's HTTP client timeout when
// positive. Zero keeps the provider's own default.
RequestTimeout time.Duration
// Transport replaces the provider's HTTP transport when non-nil. A
// transport that applies platform auth keeps doing so: only the
// connection layer beneath it is replaced.
Transport http.RoundTripper
// RateLimiter, when non-nil, makes every request the provider sends wait for
// a token first (see RateLimitTransport). It sits outside any auth layer, so a
// request is signed after its wait, not before. Build it with
// NewRequestLimiter; each provider should get its own.
RateLimiter *rate.Limiter
}
HTTPTuning carries the request-tuning settings a provider file can declare for a capability provider (tts, stt, embedding, inference, rerank): custom headers, a per-request timeout, a pre-built HTTP transport and a request rate limit. The zero value changes nothing.
func (HTTPTuning) Client ¶ added in v2.12.0
func (t HTTPTuning) Client(c *http.Client) *http.Client
Client returns a tuned copy of c; c itself is not modified. A nil c is treated as an empty client.
func (HTTPTuning) IsZero ¶ added in v2.12.0
func (t HTTPTuning) IsZero() bool
IsZero reports whether t carries no settings.
type ImageProvider ¶
type ImageProvider interface {
Provider
Generate(ctx context.Context, req ImageRequest) (ImageResponse, error)
}
ImageProvider generates images from prompts.
type ImageRequest ¶
type ImageRequest struct {
Prompt string
Size string // e.g. "1024x1024"
Quality string // e.g. "standard" | "hd"
Count int // default 1
Hints map[string]string
}
ImageRequest carries parameters for an image generation call.
type ImageResponse ¶
type ImageResponse struct {
Images [][]byte
MIMEType string
Cost *types.CostInfo
Latency time.Duration
}
ImageResponse holds generated image bytes and metadata from a provider.
type Implementation ¶
type Implementation struct {
// contains filtered or unexported fields
}
Implementation is an embeddable struct that supplies default Provider method implementations for a provider. Concrete impls populate the fields in their constructor and override any methods (Validate, Init, HealthCheck, Close) that need real behavior.
func NewImplementation ¶
func NewImplementation(name string, typ ProviderType, pricing *PricingDescriptor) *Implementation
NewImplementation constructs a helper. Pass nil pricing for free / local providers.
func (*Implementation) Close ¶
func (i *Implementation) Close() error
Close releases resources. Default no-op.
func (*Implementation) HealthCheck ¶
func (i *Implementation) HealthCheck(ctx context.Context) error
HealthCheck reports liveness. Default no-op.
func (*Implementation) Init ¶
func (i *Implementation) Init(ctx context.Context) error
Init performs asynchronous setup (network, warm-up). Default no-op.
func (*Implementation) MessageMetadataTemplate ¶ added in v2.14.0
func (i *Implementation) MessageMetadataTemplate() string
MessageMetadataTemplate returns the template that renders a message's application metadata for the model ("" when none is set). Safe to call on a nil receiver, for the same reason as Pricing.
func (*Implementation) Name ¶
func (i *Implementation) Name() string
Name returns the provider's unique registry name.
func (*Implementation) Pricing ¶
func (i *Implementation) Pricing() *PricingDescriptor
Pricing returns the configured pricing descriptor (may be nil). Safe to call on a nil receiver — a provider struct built via a raw literal (common in tests) that skips NewImplementation has a nil *Implementation, and this must degrade to "no pricing configured" rather than panic.
func (*Implementation) SetMessageMetadataTemplate ¶ added in v2.14.0
func (i *Implementation) SetMessageMetadataTemplate(t string)
SetMessageMetadataTemplate sets the template MessageMetadataTemplate returns (applied from the provider spec after construction).
func (*Implementation) SetPricing ¶
func (i *Implementation) SetPricing(p *PricingDescriptor)
SetPricing allows post-construction pricing wiring (used when the resolver fills in pricing after Init completes).
func (*Implementation) Type ¶
func (i *Implementation) Type() ProviderType
Type returns the capability type.
func (*Implementation) Validate ¶
func (i *Implementation) Validate() error
Validate performs synchronous config validation. Default no-op.
type InferenceProvider ¶
type InferenceProvider interface {
Provider
}
InferenceProvider is the shared interface for chat / realtime / multimodal LLM providers. The full surface (Predict, PredictStream, etc.) is defined in runtime/providers/provider.go and embedded here via the existing providers.Provider interface, kept intact for back-compat.
It adds no methods of its own beyond Provider; it exists as the shared name for inference-role providers.
type InlinePricingResolver ¶
type InlinePricingResolver struct {
// contains filtered or unexported fields
}
InlinePricingResolver returns descriptors registered at construction time (typically by the config loader). Lookup is keyed by (impl, model, capability).
func NewInlinePricingResolver ¶
func NewInlinePricingResolver() *InlinePricingResolver
NewInlinePricingResolver creates an empty resolver.
func (*InlinePricingResolver) Register ¶
func (r *InlinePricingResolver) Register(ref PricingRef, desc *PricingDescriptor)
Register stores a pricing descriptor under the given reference.
func (*InlinePricingResolver) Resolve ¶
func (r *InlinePricingResolver) Resolve(ctx context.Context, ref PricingRef) (*PricingDescriptor, error)
Resolve returns the registered descriptor for ref, or an error if none.
type LineItem ¶
type LineItem struct {
Unit string `json:"unit"`
Quantity float64 `json:"quantity"`
Rate float64 `json:"rate"`
USD float64 `json:"usd"`
Dimensions map[string]string `json:"dimensions,omitempty"`
}
LineItem is one row of a cost breakdown for reports.
func ComputeCost ¶
func ComputeCost(desc *PricingDescriptor, info *types.CostInfo) (totalUSD float64, breakdown []LineItem, err error)
ComputeCost multiplies raw quantities by matching rates from the pricing descriptor. Returns total USD, the breakdown, and an error if ANY nonzero unit lacks a match (back-compat: callers relying on the strict error).
nil pricing returns zero cost without error (free / local provider).
type PriceItem ¶
type PriceItem struct {
Unit string `json:"unit"`
Rate float64 `json:"rate"`
Dimensions map[string]string `json:"dimensions,omitempty"`
}
PriceItem is one line of a pricing table: a rate per unit, optionally scoped by dimensions (e.g. image size + quality).
func (*PriceItem) UnmarshalJSON ¶
UnmarshalJSON normalizes the per-1M alias form into the canonical PriceItem shape.
type PricingDescriptor ¶
type PricingDescriptor struct {
Source PricingSource `json:"source"`
PricingCorrectAt time.Time `json:"correct_at,omitempty"`
Currency string `json:"currency,omitempty"` // default "usd"
Items []PriceItem `json:"items"`
}
PricingDescriptor is the runtime-resolved pricing for a single provider+capability.
func PricingFromAdditionalConfig ¶
func PricingFromAdditionalConfig(additional map[string]any) *PricingDescriptor
PricingFromAdditionalConfig extracts a *PricingDescriptor from a provider spec's AdditionalConfig map (under the "pricing" key) by JSON-round-tripping the value into the typed descriptor. Returns nil when the key is absent or the value can't be coerced — callers fall back to package-level defaults.
Used by the TTS and STT factories that translate pkg/config provider specs into runtime services.
func ResolveLLMPricing ¶
func ResolveLLMPricing( configDesc *PricingDescriptor, flat FlatPricing, table map[string]*PricingDescriptor, model string, ) *PricingDescriptor
ResolveLLMPricing selects the pricing descriptor for a model, in order: explicit config descriptor > flat config pricing > embedded default table.
A provider that ships a table is a paid one, so a model missing from it resolves to an empty descriptor: PriceUsage then warns about every nonzero unit instead of reporting a silent $0. With no table (a self-hosted server such as vLLM) and no config, it returns nil, which prices at $0 quietly.
type PricingRef ¶
type PricingRef struct {
Impl string
Model string
Capability ProviderType
Hints map[string]string
}
PricingRef identifies what we're pricing — the resolver maps this to a PricingDescriptor.
type PricingResolver ¶
type PricingResolver interface {
Resolve(ctx context.Context, ref PricingRef) (*PricingDescriptor, error)
}
PricingResolver returns a PricingDescriptor for a given reference. Foundation PR ships only InlinePricingResolver; future work may add a remote impl that calls out to a service.
type PricingSource ¶
type PricingSource string
PricingSource discriminates how pricing values are obtained.
const ( // PricingSourceInline reads pricing from the loaded YAML descriptor. PricingSourceInline PricingSource = "inline" // PricingSourceRemote is reserved; see RemotePricingResolver (future work). PricingSourceRemote PricingSource = "remote" )
type Provider ¶
type Provider interface {
Name() string
Type() ProviderType
Pricing() *PricingDescriptor
Validate() error
Init(ctx context.Context) error
HealthCheck(ctx context.Context) error
Close() error
}
Provider is implemented by every provider type. It carries only the cross-cutting surface that the registry, config loader, metric collector, and cost rollup need.
type ProviderType ¶
type ProviderType string
ProviderType discriminates capability types. Used as a registry key, metric label, and span attribute.
const ( ProviderTypeInference ProviderType = "inference" ProviderTypeTTS ProviderType = "tts" ProviderTypeSTT ProviderType = "stt" ProviderTypeEmbedding ProviderType = "embedding" ProviderTypeImage ProviderType = "image" ProviderTypeVideo ProviderType = "video" ProviderTypeRerank ProviderType = "rerank" )
Defined ProviderType values. New types should be added here and to AllProviderTypes.
func AllProviderTypes ¶
func AllProviderTypes() []ProviderType
AllProviderTypes returns every defined ProviderType. Used by the metric collector to pre-register ancillary metric families.
func ParseProviderType ¶
func ParseProviderType(s string) (ProviderType, error)
ParseProviderType validates and returns a ProviderType from a string.
type RateLimitTransport ¶ added in v2.17.0
type RateLimitTransport struct {
Next http.RoundTripper
Limiter TokenWaiter
Timeout time.Duration
Authorize func(ctx context.Context, req *http.Request) error
}
RateLimitTransport is a RoundTripper that waits for a token from Limiter before handing each request to Next (http.DefaultTransport when nil). The wait ends early when the request's context is done: a canceled request returns context.Canceled, and one whose turn falls past its deadline returns ErrRateLimitPastDeadline. Neither is sent. A nil Limiter does not wait.
Timeout, when positive, bounds each request from the moment its wait ends, exactly as http.Client.Timeout would (through the response body), so time spent waiting for a token does not count against it. ApplyRateLimit moves a client's Timeout here: http.Client.Timeout puts a deadline on the request before any RoundTripper runs, which would make the wait eat the timeout and refuse every request whose turn is further off than the timeout.
Authorize, when set, applies the sender's credential to a copy of each request after its wait ends and before it is sent, so a SigV4 signature or a bearer token is never older than the wait. It runs once per request: the sender does not apply the credential while building a request that goes through this transport. An Authorize error fails the request without sending it.
A redirect hop is a request of its own, with its own wait. http.Client builds a hop's headers from the original request, which carries no credential, so a hop to the same scheme and host as the original request is authorized after its wait like any other. A hop to another scheme or host is never authorized, so the credential does not follow a redirect off the origin.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry stores providers keyed by (name, capability).
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry creates an empty registry with an InlinePricingResolver.
func (*Registry) CloseAll ¶
CloseAll calls Close on every registered provider, returning the first error encountered.
func (*Registry) Get ¶
func (r *Registry) Get(name string, typ ProviderType) (Provider, error)
Get returns the provider registered under (name, capability), or an error.
func (*Registry) GetAll ¶
func (r *Registry) GetAll(typ ProviderType) []Provider
GetAll returns every provider of the given capability.
func (*Registry) PricingResolver ¶
func (r *Registry) PricingResolver() PricingResolver
PricingResolver returns the registry's resolver (used by provider constructors at registration time).
func (*Registry) Register ¶
Register adds a provider. Returns an error if (name, capability) is already registered.
func (*Registry) Replace ¶ added in v2.17.0
Replace adds a provider, replacing any provider already registered under the same (name, capability). Use it where a later registration is meant to win; Register keeps the first.
func (*Registry) SetPricingResolver ¶
func (r *Registry) SetPricingResolver(res PricingResolver)
SetPricingResolver injects a non-default resolver (used by tests / future remote impl).
func (*Registry) Unregister ¶ added in v2.17.0
func (r *Registry) Unregister(name string, typ ProviderType) bool
Unregister removes the provider registered under (name, capability). It reports whether one was registered. The provider is not closed.
type STTProvider ¶
type STTProvider interface {
Provider
Transcribe(ctx context.Context, req STTRequest) (STTResponse, error)
}
STTProvider transcribes audio to text.
type STTRequest ¶
STTRequest carries audio input for a speech-to-text transcription call.
type STTResponse ¶
STTResponse holds the transcribed text and metadata from an STT provider.
type SpanArgs ¶
type SpanArgs struct {
Capability ProviderType
Operation string // "predict" | "synthesize" | "transcribe" | "embed" | "generate"
Provider string // base.Provider.Name()
Impl string // implementation discriminator (e.g. "openai", "imagen")
Model string
}
SpanArgs carries the standard attributes for a capability-scoped provider span.
type TTSProvider ¶
type TTSProvider interface {
Provider
SynthesizeTTS(ctx context.Context, req TTSRequest) (TTSStream, error)
}
TTSProvider produces audio from text. Streaming-first: every TTS call returns a TTSStream regardless of whether the underlying provider supports incremental synthesis. Buffered consumers can use ReadAllAudio to collect all chunks into a []byte.
The method is named SynthesizeTTS rather than Synthesize to avoid a naming conflict with the legacy tts.Service.Synthesize method that takes (text string, config SynthesisConfig). Both interfaces can be satisfied by the same concrete type simultaneously.
type TTSRequest ¶
type TTSRequest struct {
Text string
Voice string
Speed float32
Format string // audio format hint, e.g. "mp3", "pcm" (provider-specific)
SampleRate int // desired output sample rate in Hz (0 = provider default)
Hints map[string]string // additional dimension hints passed to pricing
}
TTSRequest carries parameters for a text-to-speech synthesis call.
type TTSStream ¶
type TTSStream interface {
// Chunks returns the channel of audio chunks. Caller must drain to
// completion or call Close to release resources. The channel closes
// when synthesis completes successfully or on error.
Chunks() <-chan audio.Chunk
// Cost returns the total cost of this synthesis. Returns nil before
// the chunk channel has closed; returns a populated *types.CostInfo
// afterwards. Pricing comes from the provider's PricingDescriptor.
Cost() *types.CostInfo
// Close cancels an in-progress stream and releases resources.
// Safe to call multiple times.
Close() error
}
TTSStream is the streaming output of a TTS provider's Synthesize call. It exposes the chunk channel that downstream pipeline stages consume, plus a typed accessor for the total cost (available once the chunk channel closes) and a Close method for early cancellation.
type TokenUsage ¶
type TokenUsage struct {
Input int // full-price uncached input
CacheRead int
CacheWrite int
Output int // visible output only
Reasoning int
AudioInput int
AudioOutput int
ImageInput int
VideoInput int
ImageOutput int
// Extra carries future/uncommon units keyed by canonical unit name.
//
// Deprecated: a token count gets its own field. Usage that is not tokens
// (characters, seconds, images) is priced from a quantities map through
// MakeCostInfo, as TTS, STT and image generation do.
Extra map[string]float64
}
TokenUsage is the normalized, provider-agnostic usage a provider hands to PriceUsage. Each provider maps its wire usage into these canonical meanings, absorbing its own quirks (cache-inclusive vs -exclusive input, reasoning bundled into output vs separate) so every field means the same thing here.
func (TokenUsage) Quantities ¶
func (u TokenUsage) Quantities() map[string]float64
Quantities converts the usage into the unit-keyed map the pricing engine consumes, omitting zero-valued units.
type TokenWaiter ¶ added in v2.17.0
TokenWaiter is what RateLimitTransport waits on before each request: it returns once the request may be sent, or with an error when the request's context ends first. *rate.Limiter implements it.
type VideoProvider ¶
type VideoProvider interface {
Provider
Generate(ctx context.Context, req VideoRequest) (VideoResponse, error)
}
VideoProvider generates videos from prompts. No concrete provider implements this interface yet; it defines the shape that the video__generate tool resolves against once a provider (e.g. Veo) lands.