Documentation
¶
Overview ¶
Package providers defines the interfaces and shared machinery behind PromptKit's model providers.
It gives chat (predict) providers one abstraction, Provider, with ToolSupport for function calling and StreamInputSupport for realtime audio and video. Embedding and rerank providers have their own interfaces, EmbeddingProvider and RerankProvider. The concrete providers (openai, claude, gemini, ollama, vllm, bedrock, vertex, voyageai, cohere and others) live in subpackages and register themselves with RegisterProviderFactory, RegisterEmbeddingProviderFactory and RegisterRerankProviderFactory.
The package provides:
- PredictionRequest and PredictionResponse, the request and response types
- CreateProviderFromSpec, which builds a provider from a ProviderSpec
- BaseProvider, which carries HTTP clients, retry, rate limiting, stream concurrency limits and request helpers for provider implementations
- Streaming types (StreamChunk, StreamInputSession), pre-first-chunk stream retry, and Prometheus stream metrics
- Multimodal capability checks and media loading
- Typed errors (ProviderHTTPError, ProviderTransportError) and IsTransient
Index ¶
- Constants
- Variables
- func APIKeyFromCredential(c credentials.Credential) string
- func ApplyExtraBody(providerID string, body, extra map[string]any)
- func CapabilitySet(capabilities []string) map[string]bool
- func CheckHTTPError(resp *http.Response, url string) error
- func ClampTopN(topN, available int) int
- func DefaultRetryPolicy() pipeline.RetryPolicy
- func DoAncillaryJSONRequest(ctx context.Context, client *http.Client, providerID, apiKey string, ...) ([]byte, error)
- func DoWithRetry(ctx context.Context, policy pipeline.RetryPolicy, providerName string, ...) (*http.Response, error)
- func ExtraBody(providerID string, additional map[string]any) map[string]any
- func ExtractAPIKey(cred Credential) string
- func ExtractOrderedEmbeddings[T any](data []T, getIndex func(T) int, getEmbedding func(T) []float32, ...) ([][]float32, error)
- func HasAudioSupport(p Provider) bool
- func HasCapabilities(declared, required []string) bool
- func HasDocumentSupport(p Provider) bool
- func HasImageSupport(p Provider) bool
- func HasVideoSupport(p Provider) bool
- func HostFromURL(raw string) string
- func IntFromConfig(cfg map[string]any, key string) (int, bool)
- func IsFormatSupported(p Provider, contentType, mimeType string) bool
- func IsRetryableStreamError(err error) bool
- func IsRetryableStreamStatus(code int) bool
- func IsStreamIdleTimeout(err error) bool
- func IsTransient(err error) bool
- func IsValidationAbort(err error) bool
- func LoadFileAsBase64(filePath string) (string, error)deprecated
- func LogEmbeddingRequest(provider, model string, textCount int, start time.Time)
- func LogEmbeddingRequestWithTokens(provider, model string, textCount, tokens int, start time.Time)
- func LogRerankRequest(provider, model string, docCount, tokens int, start time.Time)
- func MarshalRequest(req any) ([]byte, error)
- func MarshalWithExtraBody(providerID string, req any, extra map[string]any) ([]byte, error)
- func MissingCapabilities(declared, required []string) []string
- func NewInstrumentedTransport(next http.RoundTripper) http.RoundTripper
- func NewPooledTransport() *http.Transport
- func NewPooledTransportWithOptions(opts HTTPTransportOptions) *http.Transport
- func NewProviderTransport(opts HTTPTransportOptions) http.RoundTripper
- func NormalizeOpenAIFinishReason(raw string) string
- func ParsePlatformHTTPError(platform string, statusCode int, body []byte) error
- func ReadErrorBody(body io.Reader) []byte
- func ReadResponseBody(body io.Reader) ([]byte, error)
- func RedactURLSecrets(s string) string
- func RegisterEmbeddingProviderFactory(providerType string, factory EmbeddingProviderFactory)
- func RegisterPlatformEmbeddingProvider(typeName string, spec PlatformEmbeddingSpec)
- func RegisterProviderFactory(providerType string, factory ProviderFactory)
- func RegisterRerankProviderFactory(providerType string, factory RerankProviderFactory)
- func RegisteredEmbeddingProviderTypes() []string
- func RegisteredProviderTypes() []string
- func RegisteredRerankProviderTypes() []string
- func RejectedParams(err error) []string
- func ResetDefaultStreamMetrics()
- func ResolveEmbeddingCredential(ctx context.Context, providerType string, cfgDir string, ...) (credentials.Credential, error)
- func ResolveMaxTokens(requested int, defaults ProviderDefaults) int
- func ResolveRerankCredential(ctx context.Context, providerType string, cfgDir string, ...) (credentials.Credential, error)
- func ResolveTemperature(req *PredictionRequest, def float32) float32
- func RetryCall[T any](b *BaseProvider, req PredictionRequest, ...) (T, error)
- func RunProviderContractTests(t *testing.T, config ProviderContractTests)
- func SetErrorResponse(predictResp *PredictionResponse, respBody []byte, start time.Time)
- func SkipIfNoCredentials(t *testing.T, provider Provider)
- func StringPtr(s string) *string
- func SupportsMultimodal(p Provider) bool
- func UnmarshalJSON(respBody []byte, v any, predictResp *PredictionResponse, start time.Time) error
- func UnmarshalResponse(body []byte, resp any) error
- func ValidateMultimodalMessage(p Provider, msg types.Message) error
- func ValidateMultimodalRequest(p Provider, req *PredictionRequest) error
- func ValidatePredictReturnsLatency(t *testing.T, provider Provider)
- func ValidatePredictWithToolsReturnsLatency(t *testing.T, provider Provider)
- func ValidateSamplingParamsAccepted(t *testing.T, provider Provider)
- func WarnUnsentParams(providerID string, req *PredictionRequest, params ...string)
- type AudioStreamingCapabilities
- type BargeInSignal
- type BaseEmbeddingProvider
- func (b *BaseEmbeddingProvider) ApplyHTTPTuning(t base.HTTPTuning) error
- func (b *BaseEmbeddingProvider) ApplyWiring(w EmbeddingWiring) (dimsExplicit bool)
- func (b *BaseEmbeddingProvider) CheckDimensions(embeddings [][]float32) error
- func (b *BaseEmbeddingProvider) DoEmbeddingRequest(ctx context.Context, cfg HTTPRequestConfig) ([]byte, error)
- func (b *BaseEmbeddingProvider) EmbedWithEmptyCheck(ctx context.Context, req EmbeddingRequest, embedFn EmbedFunc) (EmbeddingResponse, error)
- func (b *BaseEmbeddingProvider) EmbeddingDimensions() int
- func (b *BaseEmbeddingProvider) EmptyResponseForModel(model string) EmbeddingResponse
- func (b *BaseEmbeddingProvider) HandleEmptyRequest(req EmbeddingRequest) (EmbeddingResponse, bool)
- func (b *BaseEmbeddingProvider) ID() string
- func (b *BaseEmbeddingProvider) MaxBatchSize() int
- func (b *BaseEmbeddingProvider) Model() string
- func (b *BaseEmbeddingProvider) ResolveModel(reqModel string) string
- type BaseProvider
- func NewBaseProvider(id string, includeRawOutput bool, client *http.Client) BaseProvider
- func NewBaseProviderWithAPIKey(id string, includeRawOutput bool, primaryKey, fallbackKey string) (provider BaseProvider, apiKey string)
- func NewBaseProviderWithCredential(id string, includeRawOutput bool, timeout time.Duration, cred Credential) (bp BaseProvider, apiKey string)
- func (b *BaseProvider) AcquireStreamSlot(ctx context.Context) error
- func (b *BaseProvider) ApplyCustomHeaders(req *http.Request) error
- func (b *BaseProvider) AuthorizeRequest(ctx context.Context, req *http.Request) error
- func (b *BaseProvider) Close() error
- func (b *BaseProvider) Credential() Credential
- func (b *BaseProvider) DoAndReadResponse(req *http.Request, predictResp *PredictionResponse, start time.Time, ...) (body []byte, statusCode int, err error)
- func (b *BaseProvider) GetHTTPClient() *http.Client
- func (b *BaseProvider) GetRetryPolicy() pipeline.RetryPolicy
- func (b *BaseProvider) GetStreamingHTTPClient() *http.Client
- func (b *BaseProvider) HTTPTimeout() time.Duration
- func (b *BaseProvider) ID() string
- func (b *BaseProvider) LoggingContext(ctx context.Context, model string) context.Context
- func (b *BaseProvider) MakeJSONRequest(ctx context.Context, url string, request any, headers RequestHeaders, ...) ([]byte, error)
- func (b *BaseProvider) MakeRawRequest(ctx context.Context, url string, body []byte, headers RequestHeaders, ...) ([]byte, error)
- func (b *BaseProvider) MaxPayloadSize() int64
- func (b *BaseProvider) MediaLoader() *MediaLoader
- func (b *BaseProvider) ParamRejected(param string) bool
- func (b *BaseProvider) ParamSupported(param string) bool
- func (b *BaseProvider) RateLimiter() *rate.Limiter
- func (b *BaseProvider) RejectedParamNames() []string
- func (b *BaseProvider) ReleaseStreamSlot()
- func (b *BaseProvider) RetryRejectedParams(call func() error) error
- func (b *BaseProvider) RunStreamingRequest(ctx context.Context, req *StreamRetryRequest, consumer StreamConsumer) (<-chan StreamChunk, error)
- func (b *BaseProvider) SetAllowPrivateNetworkMedia(allow bool)
- func (b *BaseProvider) SetCredential(cred Credential)
- func (b *BaseProvider) SetCustomHeaders(headers map[string]string)
- func (b *BaseProvider) SetHTTPTimeout(timeout time.Duration)
- func (b *BaseProvider) SetHTTPTransport(rt http.RoundTripper)
- func (b *BaseProvider) SetMaxPayloadSize(size int64)
- func (b *BaseProvider) SetMediaStorageService(store storage.MediaStorageService)
- func (b *BaseProvider) SetRateLimit(requestsPerSecond float64, burst int)
- func (b *BaseProvider) SetRetryPolicy(policy pipeline.RetryPolicy)
- func (b *BaseProvider) SetStreamIdleTimeout(d time.Duration)
- func (b *BaseProvider) SetStreamObserver(o StreamObserver)
- func (b *BaseProvider) SetStreamRetryBudget(budget *RetryBudget)
- func (b *BaseProvider) SetStreamRetryPolicy(policy StreamRetryPolicy)
- func (b *BaseProvider) SetStreamSemaphore(sem *StreamSemaphore)
- func (b *BaseProvider) SetUnsupportedParams(params []string)
- func (b *BaseProvider) ShouldIncludeRawOutput() bool
- func (b *BaseProvider) StreamIdleTimeout() time.Duration
- func (b *BaseProvider) StreamRetryBudget() *RetryBudget
- func (b *BaseProvider) StreamRetryPolicy() StreamRetryPolicy
- func (b *BaseProvider) StreamSemaphore() *StreamSemaphore
- func (b *BaseProvider) SupportsStreaming() bool
- func (b *BaseProvider) WaitForRateLimit(ctx context.Context) error
- func (b *BaseProvider) WithMedia(m MediaSettings) BaseProvider
- type BaseRerankProvider
- func (b *BaseRerankProvider) ApplyHTTPTuning(t base.HTTPTuning) error
- func (b *BaseRerankProvider) DoRerankRequest(ctx context.Context, cfg HTTPRequestConfig) ([]byte, error)
- func (b *BaseRerankProvider) ID() string
- func (b *BaseRerankProvider) MaxDocuments() int
- func (b *BaseRerankProvider) Model() string
- func (b *BaseRerankProvider) RerankWithEmptyCheck(ctx context.Context, req RerankRequest, ...) (RerankResponse, error)
- func (b *BaseRerankProvider) ResolveModel(reqModel string) string
- type BedrockEventScanner
- type BedrockEventStreamFrameDetector
- type ContextWindowProvider
- type Credential
- type DoRequestFunc
- type EmbedFunc
- type EmbeddingProvider
- type EmbeddingProviderFactory
- type EmbeddingProviderSpec
- type EmbeddingRequest
- type EmbeddingResponse
- type EmbeddingTransport
- type EmbeddingUsage
- type EmbeddingWiring
- type ExecutionResult
- type FrameDetector
- type HTTPRequestConfig
- type HTTPTransportOptions
- type IdleTimeoutReader
- type ImageDetail
- type InferenceProvider
- type JSONArrayFrameDetector
- type JitterHealthReporter
- type LateInputTranscriber
- type MediaLoader
- type MediaLoaderConfig
- type MediaScoped
- type MediaSettings
- type MediaStorageConfigurable
- type MessageMetadataTemplater
- type MockRerankOption
- type MockRerankProvider
- type MultimodalCapabilities
- type MultimodalCapabilityProvider
- type NDJSONFrameDetector
- type PlatformConfig
- type PlatformEmbeddingSpec
- type PredictionRequest
- type PredictionResponse
- type Pricing
- type PrivateNetworkMediaConfigurable
- type Provider
- type ProviderContractTests
- type ProviderDefaults
- type ProviderFactory
- type ProviderHTTPError
- type ProviderSpec
- type ProviderTools
- type ProviderTransportError
- type RankedDocument
- type RateLimitOptions
- type Registry
- func (r *Registry) Base() *base.Registry
- func (r *Registry) Close() error
- func (r *Registry) Get(id string) (Provider, bool)
- func (r *Registry) GetAll(typ base.ProviderType) []base.Provider
- func (r *Registry) GetByType(name string, typ base.ProviderType) (base.Provider, error)
- func (r *Registry) List() []string
- func (r *Registry) Register(provider Provider)
- type RequestHeaders
- type RerankProvider
- type RerankProviderFactory
- type RerankProviderSpec
- type RerankRequest
- type RerankResponse
- type RerankTransport
- type RerankUsage
- type ResponseFormat
- type ResponseFormatType
- type RetryBudget
- type RetryableHTTPError
- type SSEFrameDetector
- type SSEScanner
- type SendableContentProvider
- type StreamChunk
- type StreamConsumer
- type StreamEvent
- type StreamEventObserver
- type StreamInputSession
- type StreamInputSupport
- type StreamMediaData
- type StreamMetrics
- func (m *StreamMetrics) ConcurrencyRejected(provider, reason string)
- func (m *StreamMetrics) FrameDropAdd(direction, reason string, n int)
- func (m *StreamMetrics) FrameDropsVec() *prometheus.CounterVec
- func (m *StreamMetrics) FrameUnderrunInc(direction string)
- func (m *StreamMetrics) FrameUnderrunSamplesAdd(direction string, n int)
- func (m *StreamMetrics) FrameUnderrunSamplesVec() *prometheus.CounterVec
- func (m *StreamMetrics) FrameUnderrunsVec() *prometheus.CounterVec
- func (m *StreamMetrics) HTTPConnsInUseDec(host string)
- func (m *StreamMetrics) HTTPConnsInUseInc(host string)
- func (m *StreamMetrics) ObserveFirstChunkLatency(provider string, d time.Duration)
- func (m *StreamMetrics) ObserveRetryBudgetAvailable(provider, host string, budget *RetryBudget)
- func (m *StreamMetrics) ObserveStreamErrorChunksForwarded(provider string, chunks int)
- func (m *StreamMetrics) PacingBehindDeadlineInc(direction string)
- func (m *StreamMetrics) PacingBehindDeadlineVec() *prometheus.CounterVec
- func (m *StreamMetrics) PipelineStageAudioBytesAdd(stage string, bytes int)
- func (m *StreamMetrics) PipelineStageAudioBytesVec() *prometheus.CounterVec
- func (m *StreamMetrics) PipelineStageElementInc(stage string)
- func (m *StreamMetrics) PipelineStageElementsVec() *prometheus.CounterVec
- func (m *StreamMetrics) ProviderCallsInFlightDec(provider string)
- func (m *StreamMetrics) ProviderCallsInFlightInc(provider string)
- func (m *StreamMetrics) ProviderRetry(provider, outcome string)
- func (m *StreamMetrics) RetryAttempt(provider, outcome string)
- func (m *StreamMetrics) StreamsInFlightDec(provider string)
- func (m *StreamMetrics) StreamsInFlightInc(provider string)
- type StreamObserver
- type StreamPump
- type StreamRetryPolicy
- func (p StreamRetryPolicy) Attempts() int
- func (p StreamRetryPolicy) BackoffFor(attempt int) time.Duration
- func (p StreamRetryPolicy) InitialDelayOrDefault() time.Duration
- func (p StreamRetryPolicy) MaxDelayOrDefault() time.Duration
- func (p StreamRetryPolicy) MaxRetryAfterOrDefault() time.Duration
- func (p StreamRetryPolicy) RetryDelay(attempt int, retryAfter time.Duration) (delay time.Duration, ok bool)
- type StreamRetryRequest
- type StreamRetryResult
- type StreamRetryWindow
- type StreamScanner
- type StreamSemaphore
- type StreamingCapabilities
- type StreamingInputConfig
- type StreamingSampling
- type StreamingToolDefinition
- type ToolDescriptor
- type ToolResponse
- type ToolResponseSupport
- type ToolResult
- type ToolSupport
- type UnsupportedContentError
- type UnsupportedProviderError
- type UnsupportedProviderPlatformError
- type ValidationAbortError
- type VideoResolution
- type VideoStreamingCapabilities
Examples ¶
Constants ¶
const ( ContentTypeHeader = "Content-Type" AuthorizationHeader = "Authorization" ApplicationJSON = "application/json" BearerPrefix = "Bearer " )
Common HTTP constants for embedding providers.
const ( DefaultMaxIdleConns = 1000 DefaultMaxIdleConnsPerHost = 100 // DefaultMaxConnsPerHost is the default cap on total TCP connections // per upstream host. Zero means unlimited, matching Go's stdlib // http.Transport default. Real LLM providers enforce rate limits // server-side; a client-side connection cap adds a hidden throughput // ceiling that's hard to debug. DefaultMaxConnsPerHost = 0 DefaultIdleConnTimeout = 90 * time.Second DefaultTLSHandshakeTimeout = 10 * time.Second DefaultDialTimeout = 30 * time.Second DefaultDialKeepAlive = 30 * time.Second )
Connection pooling defaults for HTTP transports shared across providers.
const ( // MaxAggregateMediaSize is the maximum total size, in bytes, of the file, // URL and stored media one MediaLoader reads (100MB). Inline data does not // count toward it. Every built-in provider uses one loader per message, so // this is the most media one message can make a provider read; over it, // GetBase64Data returns an error wrapping ErrAggregateMediaSizeExceeded. MaxAggregateMediaSize int64 = 100 * 1024 * 1024 // MaxMediaItems is the maximum number of media items one MediaLoader loads // through GetBase64Data, counting inline data, files, URLs and storage // references. Every built-in provider uses one loader per message, so this // is the most media parts one message can have loaded; media a provider // passes to the model as a URL is not loaded and does not count. Past the // limit, GetBase64Data returns an error wrapping ErrMediaItemLimitExceeded. MaxMediaItems = 20 )
const ( CapabilityText = "text" CapabilityStreaming = "streaming" CapabilityVision = "vision" CapabilityAudio = "audio" CapabilityVideo = "video" // CapabilityTools declares tool calling for capability matching only. A // provider whose list omits it is still offered tools when it implements // ToolSupport; a requirement that names it is unmet by that list. CapabilityTools = "tools" CapabilityJSON = "json" CapabilityDocuments = "documents" )
Declared capability names used in a provider's Capabilities list.
The list does two jobs. It is the label set that capability matching (MissingCapabilities, HasCapabilities) compares a requirement against, for example to pick the providers a scenario can run on. And on the Claude, Gemini and OpenAI providers, vision, audio, video and documents set the multimodal capabilities the provider reports (ApplyDeclaredModalities), replacing per-model hardcoding. Other providers report fixed capabilities.
The list never narrows what a request carries. Request media is validated against what the adapter can send (SendableContentProvider), and tools are offered to every provider that implements ToolSupport.
const ( ParamTopK = "top_k" ParamFrequencyPenalty = "frequency_penalty" ParamPresencePenalty = "presence_penalty" )
Wire names of the optional sampling parameters WarnUnsentParams reports.
const ( ParamTemperature = "temperature" ParamTopP = "top_p" )
Wire names of the sampling parameters a provider learns its model rejects.
const ( DefaultMaxRetries = 3 DefaultInitialDelayMs = 500 DefaultBackoff = "exponential" )
Default retry constants.
const ( DefaultStreamRetryMaxAttempts = 2 DefaultStreamRetryInitialDelay = 250 * time.Millisecond DefaultStreamRetryMaxDelay = 2 * time.Second // DefaultStreamRetryMaxRetryAfter bounds how long a server's Retry-After // may hold a retry. Rate-limit responses commonly ask for tens of seconds. DefaultStreamRetryMaxRetryAfter = 60 * time.Second )
Default values for StreamRetryPolicy. They are small because streaming retry targets transient h2 stream resets, not generic 5xx storms.
const ( StreamEventChunk = "chunk" StreamEventComplete = "complete" StreamEventError = "error" )
StreamEvent types.
const (
// DefaultGeminiBaseURL is the default base URL for Gemini API (includes version path)
DefaultGeminiBaseURL = "https://generativelanguage.googleapis.com/v1beta"
)
const ( // DefaultMaxPayloadSize is the default maximum request payload size (100 MB). // This is generous but prevents accidentally sending multi-GB payloads. DefaultMaxPayloadSize int64 = 100 * 1024 * 1024 )
Payload size limits.
const DefaultStreamBufferSize = 32
DefaultStreamBufferSize is the default buffer size for streaming channels. A buffer of 32 prevents the streaming goroutine from blocking on every send when the consumer is slow, while keeping memory usage reasonable.
const DefaultStreamIdleTimeout = 30 * time.Second
DefaultStreamIdleTimeout is the maximum time to wait between stream chunks before considering the stream stalled. If no data is received within this duration, the response body is closed to unblock the reader.
const ExtraBodyConfigKey = "extra_body"
ExtraBodyConfigKey is the additional_config key whose map is merged into the request body of the OpenAI-compatible chat providers (openai, vllm, ollama), like the OpenAI SDK's extra_body. It carries server-specific request parameters PromptKit has no field for, such as vLLM's chat_template_kwargs:
additional_config:
extra_body:
chat_template_kwargs:
enable_thinking: false
A field the provider sets itself (model, messages, tools, stream, ...) always wins; the colliding extra_body field is dropped with a warning.
const MaxErrorResponseSize int64 = 1 << 20
MaxErrorResponseSize is the maximum size for error response bodies (1 MB). Error responses should be small; this prevents reading huge bodies on failures.
const MaxTokensUnlimited = -1
MaxTokensUnlimited is the ProviderDefaults.MaxTokens value that asks the provider to send no output-token limit, so the model's own maximum applies. Claude requires a limit on every request and rejects it at construction.
Variables ¶
var ( // ErrMediaItemLimitExceeded is returned by MediaLoader.GetBase64Data when // the loader has already loaded MaxMediaItems items. Every built-in // provider uses one loader per message, so it means a single message // carries more than MaxMediaItems media parts the provider must load. ErrMediaItemLimitExceeded = errors.New("media item limit exceeded") // ErrAggregateMediaSizeExceeded is returned by MediaLoader.GetBase64Data // when the file, URL and stored media the loader has read total more than // MaxAggregateMediaSize bytes. Every built-in provider uses one loader per // message, so it means a single message's media is over that size. ErrAggregateMediaSizeExceeded = errors.New("aggregate media size limit exceeded") )
var ErrPayloadTooLarge = errors.New("request payload too large")
ErrPayloadTooLarge is returned when a request payload exceeds the provider's configured maximum size (see BaseProvider.SetMaxPayloadSize).
var ErrStreamIdleTimeout = errors.New("stream idle timeout: no data received")
ErrStreamIdleTimeout is returned when no data is received within the idle timeout.
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). Embedding providers only need the key string, not the full header-application machinery. Per-provider init() functions use it to build their factory closures.
func ApplyExtraBody ¶ added in v2.13.0
ApplyExtraBody adds each extra field to body unless body already sets it.
func CapabilitySet ¶
CapabilitySet converts a declared capability list into a membership set for O(1) lookup. It returns nil for an empty list so callers can distinguish "not declared" (nil, fall back to built-in defaults) from a non-empty declaration that is authoritative.
func CheckHTTPError ¶
CheckHTTPError checks if HTTP response is an error and returns formatted error with body
func ClampTopN ¶ added in v2.1.0
ClampTopN returns the number of results to keep: TopN when it is set and smaller than what came back, otherwise everything. Vendors that honor top_n server-side still call this, because a provider is free to return more than asked and the interface promises it never does.
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() pipeline.RetryPolicy
DefaultRetryPolicy returns the RetryPolicy providers start with: 3 retries, exponential backoff, 500ms initial delay.
func DoAncillaryJSONRequest ¶ added in v2.1.0
func DoAncillaryJSONRequest( ctx context.Context, client *http.Client, providerID, apiKey string, cfg HTTPRequestConfig, ) ([]byte, error)
DoAncillaryJSONRequest POSTs a JSON body for one of the ancillary provider roles (embedding, rerank) and returns the raw response body.
A transport failure returns a *ProviderTransportError, whose Error() redacts credential-bearing query parameters and which IsTransient classifies as transient. A non-200 status returns a *ProviderHTTPError. The request sets Authorization to "Bearer <apiKey>" only when cfg.UseAPIKey is true and apiKey is not empty.
func DoWithRetry ¶
func DoWithRetry( ctx context.Context, policy pipeline.RetryPolicy, providerName string, doFn DoRequestFunc, ) (*http.Response, error)
DoWithRetry executes doFn with retry logic according to the given policy. It retries on retryable HTTP status codes (429, 502, 503, 504) and transient network errors, and never after context cancellation. A Retry-After header on a retryable response replaces the computed backoff delay. The body of a retryable response is closed before retrying. The caller closes the body of a successful response.
When every attempt fails with a retryable status, DoWithRetry returns the last response, whose body is already closed, together with a *RetryableHTTPError.
func ExtraBody ¶ added in v2.13.0
ExtraBody returns the extra_body map from a provider's additional_config, or nil when there is none. A value that is not a JSON-encodable map is ignored with a warning naming the provider, so a mistyped extra_body is visible rather than silently doing nothing.
func ExtractAPIKey ¶
func ExtractAPIKey(cred Credential) string
ExtractAPIKey extracts an API key string from a Credential, if it is an APIKeyCredential. Returns an empty string if the credential is nil, not an api_key type, or does not implement the APIKey() method.
func ExtractOrderedEmbeddings ¶
func ExtractOrderedEmbeddings[T any]( data []T, getIndex func(T) int, getEmbedding func(T) []float32, expectedCount int, ) ([][]float32, error)
ExtractOrderedEmbeddings places each item's embedding at the position getIndex reports, in a slice of expectedCount entries. It returns an error when the response does not hold exactly one embedding per input: a count other than expectedCount, an index outside [0, expectedCount), or an index that appears twice. Each case would otherwise hand the caller a nil vector in place of one it asked for.
func HasAudioSupport ¶
HasAudioSupport checks if a provider supports audio inputs
func HasCapabilities ¶ added in v2.18.0
HasCapabilities reports whether declared lists every capability in required. See MissingCapabilities.
func HasDocumentSupport ¶
HasDocumentSupport checks if a provider supports document inputs
func HasImageSupport ¶
HasImageSupport checks if a provider supports image inputs
func HasVideoSupport ¶
HasVideoSupport checks if a provider supports video inputs
func HostFromURL ¶
HostFromURL extracts only the host portion (without scheme or path) from a URL string, intended for use as a Prometheus label on streaming metrics. It returns an empty string on a parse error or when the URL has no host; callers treat an empty label as an unknown host.
func IntFromConfig ¶
IntFromConfig returns cfg[key] coerced to int, supporting the common YAML number shapes (int, int64, float64). Returns ok=false when the key is missing or the value isn't numeric.
func IsFormatSupported ¶
IsFormatSupported checks if a provider supports a specific media format (MIME type)
func IsRetryableStreamError ¶
IsRetryableStreamError returns true if the error looks like a transient streaming failure that is safe to retry from the pre-first-chunk window.
It accepts what IsTransient accepts, retryable network errors, and errors whose text names an h2 stream reset, GOAWAY, TCP reset, broken pipe or unexpected EOF. It never accepts context cancellation, a deadline, or application-layer parse errors.
func IsRetryableStreamStatus ¶
IsRetryableStreamStatus returns true for HTTP status codes that are worth retrying on a streaming request: 429, 502, 503 and 504.
func IsStreamIdleTimeout ¶
IsStreamIdleTimeout checks if an error is (or wraps) a stream idle timeout.
func IsTransient ¶
IsTransient returns true if err represents a transient provider failure (retryable HTTP status or connection-level error). Uses errors.As to traverse wrapped error chains. Context cancellation and deadline errors are never transient, and neither is a stream idle timeout.
func IsValidationAbort ¶
IsValidationAbort reports whether err is a *ValidationAbortError. It does not unwrap wrapped errors.
func LoadFileAsBase64
deprecated
LoadFileAsBase64 reads a file and returns its content as a base64-encoded string.
Deprecated: Use MediaLoader.GetBase64Data instead for better functionality including storage reference support, URL loading, and proper context handling.
This function is kept for backward compatibility. It delegates to the MediaLoader implementation.
func LogEmbeddingRequest ¶
LogEmbeddingRequest logs a completed embedding request with common fields.
func LogEmbeddingRequestWithTokens ¶
LogEmbeddingRequestWithTokens logs a completed embedding request with token count.
func LogRerankRequest ¶ added in v2.1.0
LogRerankRequest records a completed rerank at debug level, matching the embedding path's logging so the two roles read alike in a trace.
func MarshalRequest ¶
MarshalRequest marshals a request body to JSON with standardized error handling.
func MarshalWithExtraBody ¶ added in v2.13.0
MarshalWithExtraBody marshals req, a JSON object, and merges extra into it as ApplyExtraBody does. With no extra fields it is json.Marshal.
func MissingCapabilities ¶ added in v2.18.0
MissingCapabilities returns the entries of required that declared does not list, in the order required names them and each at most once. Names are compared exactly, so "tools" matches CapabilityTools and nothing else. A nil result means declared covers every requirement.
func NewInstrumentedTransport ¶
func NewInstrumentedTransport(next http.RoundTripper) http.RoundTripper
NewInstrumentedTransport wraps an http.RoundTripper with OpenTelemetry instrumentation. This propagates trace context (W3C traceparent header) on outgoing requests and creates client-side HTTP spans. When no TracerProvider is configured, the wrapper is a near-zero-cost passthrough.
func NewPooledTransport ¶
NewPooledTransport creates an *http.Transport configured with default connection pooling settings suitable for high-throughput provider communication. Equivalent to NewPooledTransportWithOptions(HTTPTransportOptions{}).
func NewPooledTransportWithOptions ¶
func NewPooledTransportWithOptions(opts HTTPTransportOptions) *http.Transport
NewPooledTransportWithOptions creates an *http.Transport with the given pool configuration. Zero-valued fields in opts fall back to the package-level defaults. The resulting transport is otherwise identical to NewPooledTransport (same TLS minimum version, same dial timeouts, same HTTP/2 upgrade policy).
func NewProviderTransport ¶ added in v2.12.0
func NewProviderTransport(opts HTTPTransportOptions) http.RoundTripper
NewProviderTransport builds the transport every completion provider runs on: a pooled transport configured from opts, wrapped with OpenTelemetry instrumentation and connection tracking (the http_conns_in_use gauge). Zero-valued options fall back to package defaults.
Capability providers (tts, stt, embedding, inference, rerank) get this transport only when their provider file sets http_transport.
func NormalizeOpenAIFinishReason ¶
NormalizeOpenAIFinishReason maps an OpenAI-wire finish_reason onto the canonical vocabulary in runtime/types. Unknown (and empty) values pass through verbatim so a new provider reason is never silently swallowed. Shared by the OpenAI, vLLM, and Ollama providers, which speak this vocabulary.
func ParsePlatformHTTPError ¶
ParsePlatformHTTPError extracts a human-readable error from platform-specific HTTP error responses (Bedrock, Vertex, Azure). These platforms return JSON like {"message":"..."} on HTTP 4xx/5xx. Falls back to raw body if parsing fails. When platform is empty, returns a generic error with the raw body.
func ReadErrorBody ¶
ReadErrorBody reads and returns an error response body, limiting the size to MaxErrorResponseSize. Error responses should be small; this is a safety net.
func ReadResponseBody ¶
ReadResponseBody reads and returns the response body, limiting the size to DefaultMaxPayloadSize to prevent unbounded memory consumption.
func RedactURLSecrets ¶
RedactURLSecrets masks credential-bearing query parameters in any URLs found in s, leaving the rest of the string untouched.
It exists because credentials in URLs reach logs through error strings, not through the logger. Gemini carries its API key as `?key=`, Go's *url.Error embeds the full URL, and every layer that wraps that error reformats the same text, so one transport failure can write a live key to the log several times over. Redacting where the error is FORMATTED covers every wrapping layer at once, and covers every provider.
This is a backstop, not the primary defense. A credential is better kept out of the URL entirely — see the Gemini provider's x-goog-api-key header.
The host, path and non-secret parameters are preserved: an error that cannot say which endpoint failed is not much use.
func RegisterEmbeddingProviderFactory ¶
func RegisterEmbeddingProviderFactory(providerType string, factory EmbeddingProviderFactory)
RegisterEmbeddingProviderFactory registers a factory for the given provider type. Typically called from per-provider package init(). Re-registration overwrites silently, as RegisterProviderFactory does for chat providers.
func RegisterPlatformEmbeddingProvider ¶
func RegisterPlatformEmbeddingProvider(typeName string, spec PlatformEmbeddingSpec)
RegisterPlatformEmbeddingProvider registers an embedding factory that enforces the platform block, resolves the transport, and delegates to Build.
Platform-native providers have no API-key mode: without a platform block there is no signer or token source, so the factory returns an error at construction instead of sending unauthenticated requests.
func RegisterProviderFactory ¶
func RegisterProviderFactory(providerType string, factory ProviderFactory)
RegisterProviderFactory registers a factory function for a provider type
func RegisterRerankProviderFactory ¶ added in v2.1.0
func RegisterRerankProviderFactory(providerType string, factory RerankProviderFactory)
RegisterRerankProviderFactory registers a factory for the given provider type. Typically called from a per-provider package init(). Re-registration overwrites silently, matching the embedding and chat paths.
func RegisteredEmbeddingProviderTypes ¶
func RegisteredEmbeddingProviderTypes() []string
RegisteredEmbeddingProviderTypes returns the embedding provider types with a registered factory, sorted. Use it to check a configured type before CreateEmbeddingProviderFromSpec rather than constructing and parsing the error.
func RegisteredProviderTypes ¶
func RegisteredProviderTypes() []string
RegisteredProviderTypes returns the completion (chat) provider types with a registered factory, sorted. CreateProviderFromSpec resolves against this registry for the llm, image and video roles alike, so a type listed here constructs for any of them.
func RegisteredRerankProviderTypes ¶ added in v2.1.0
func RegisteredRerankProviderTypes() []string
RegisteredRerankProviderTypes returns the rerank provider types with a registered factory, sorted. Use it to check a configured type before CreateRerankProviderFromSpec rather than constructing and parsing the error.
func RejectedParams ¶ added in v2.13.0
RejectedParams returns the sampling parameters err reports the API rejected for this model, or nil when err is not such a rejection. It recognizes OpenAI and Anthropic messages that name the parameter and Gemini's penalty message, and only in an error whose text contains "400".
func ResetDefaultStreamMetrics ¶
func ResetDefaultStreamMetrics()
ResetDefaultStreamMetrics clears the process-wide instance. Intended for tests only — production code should not need to reset metrics.
func ResolveEmbeddingCredential ¶
func ResolveEmbeddingCredential(ctx context.Context, providerType string, cfgDir string, cred *credentials.CredentialConfig, platform *credentials.PlatformConfig, ) (credentials.Credential, error)
ResolveEmbeddingCredential resolves an embedding provider's credential block into a concrete Credential, applying the same fallback chain as chat providers (api_key → file → env → default env vars). When platform is non-empty, the platform branch produces a platform credential (e.g. AzureCredential) instead of an API key. Exposed as a helper for the SDK runtime-config layer.
func ResolveMaxTokens ¶ added in v2.12.0
func ResolveMaxTokens(requested int, defaults ProviderDefaults) int
ResolveMaxTokens returns the output-token limit for a request: the request's own positive value, else the provider default. A zero or negative request value counts as unset, so MaxTokensUnlimited only takes effect as a provider default. A zero result means send no limit, so the model's own maximum applies.
func ResolveRerankCredential ¶ added in v2.1.0
func ResolveRerankCredential(ctx context.Context, providerType string, cfgDir string, cred *credentials.CredentialConfig, platform *credentials.PlatformConfig, ) (credentials.Credential, error)
ResolveRerankCredential resolves a rerank provider's credential block into a concrete Credential, applying the same fallback chain as the embedding and chat paths (api_key → file → env → default env vars).
func ResolveTemperature ¶ added in v2.13.0
func ResolveTemperature(req *PredictionRequest, def float32) float32
ResolveTemperature returns the temperature req sends: its own when it set one (explicitly, or any non-zero value), otherwise the provider's default def. A zero without TemperatureSet is "unset", which is what every caller that predates TemperatureSet means by it.
func RetryCall ¶ added in v2.13.0
func RetryCall[T any](b *BaseProvider, req PredictionRequest, call func(PredictionRequest) (T, error)) (T, error)
RetryCall runs call with req through b.RetryRejectedParams, after moving req's system-role messages to its System field (NormalizeMessages): the APIs reject "system" as a message role on some paths. Each provider's Predict and PredictStream are this around their single attempt.
func RunProviderContractTests ¶
func RunProviderContractTests(t *testing.T, config ProviderContractTests)
RunProviderContractTests executes all contract tests against a provider. Call it from each provider's test file. The tool and streaming checks run only when SupportsToolsExpected and SupportsStreamingExpected are set.
func SetErrorResponse ¶
func SetErrorResponse(predictResp *PredictionResponse, respBody []byte, start time.Time)
SetErrorResponse sets latency and raw body on error responses
func SkipIfNoCredentials ¶
SkipIfNoCredentials skips the test if the API refuses the credentials. Any other error is left for the test to fail on: skipping it hid a retired model. This is a helper for integration tests that need real API access.
func StringPtr ¶
StringPtr is a helper function that returns a pointer to a string. This is commonly used across provider implementations for optional fields.
func SupportsMultimodal ¶
SupportsMultimodal checks if a provider implements multimodal support
func UnmarshalJSON ¶
UnmarshalJSON unmarshals JSON with error recovery that sets latency and raw response
func UnmarshalResponse ¶
UnmarshalResponse unmarshals a response body from JSON with standardized error handling.
func ValidateMultimodalMessage ¶
ValidateMultimodalMessage checks that the provider supports the image, audio, video and document parts of a message and their MIME types. It returns an *UnsupportedContentError for the first part that fails. A message with no media parts is always valid, even when its text is carried in Parts. A part with no MIME type is checked for its modality only. A provider that implements SendableContentProvider is checked against what its adapter can send, so a config's capabilities list never narrows the check.
func ValidateMultimodalRequest ¶
func ValidateMultimodalRequest(p Provider, req *PredictionRequest) error
ValidateMultimodalRequest checks the input messages of a predict request with ValidateMultimodalMessage and returns the first *UnsupportedContentError. Assistant messages are not checked: their parts are what a model produced, not input the provider's capabilities describe, and each provider replays them in its own way.
The provider stage calls it before every predict and stream call to a provider that implements MultimodalCapabilityProvider, unless stage.ProviderConfig.SkipContentValidation is set.
func ValidatePredictReturnsLatency ¶
ValidatePredictReturnsLatency verifies that Predict() returns a response with a positive latency that is no more than ten times the measured elapsed time. It is exported for use in provider-specific regression tests.
func ValidatePredictWithToolsReturnsLatency ¶
ValidatePredictWithToolsReturnsLatency verifies that PredictWithTools() returns a response with a positive latency. It is exported for use in provider-specific regression tests.
func ValidateSamplingParamsAccepted ¶ added in v2.13.0
ValidateSamplingParamsAccepted sends every sampling parameter a prompt can set (an explicit temperature of 0, top_p, both penalties and top_k) down each request path, and fails on any API error. Unlike the other contract checks it does not skip on an error: a 400 here means the provider sends a parameter its API rejects, which is what this guards. Exported so a provider can run it against extra configurations (another API mode, a thinking model).
func WarnUnsentParams ¶ added in v2.13.0
func WarnUnsentParams(providerID string, req *PredictionRequest, params ...string)
WarnUnsentParams logs, once per provider and parameter, each of params (ParamTemperature, ParamTopP, ParamTopK, ParamFrequencyPenalty, ParamPresencePenalty) that req sets but providerID does not send, because its API rejects or has no such parameter. A parameter req leaves unset logs nothing.
Types ¶
type AudioStreamingCapabilities ¶
type AudioStreamingCapabilities struct {
// SupportedEncodings lists supported audio encodings
// Common values: "pcm", "opus", "mp3", "aac"
SupportedEncodings []string `json:"supported_encodings"`
// SupportedSampleRates lists supported sample rates in Hz
// Common values: 8000, 16000, 24000, 44100, 48000
SupportedSampleRates []int `json:"supported_sample_rates"`
// SupportedChannels lists supported channel counts
// Common values: 1 (mono), 2 (stereo)
SupportedChannels []int `json:"supported_channels"`
// SupportedBitDepths lists supported bit depths
// Common values: 16, 24, 32
SupportedBitDepths []int `json:"supported_bit_depths,omitempty"`
// PreferredEncoding is the recommended encoding for best quality/latency
PreferredEncoding string `json:"preferred_encoding"`
// PreferredSampleRate is the recommended sample rate
PreferredSampleRate int `json:"preferred_sample_rate"`
}
AudioStreamingCapabilities describes audio streaming support.
type BargeInSignal ¶
type BargeInSignal struct {
// contains filtered or unexported fields
}
BargeInSignal is the shared implementation of StreamInputSession.BargeIn(). Streaming sessions embed it so every provider exposes barge-in identically — the only per-provider code is the one line that calls SignalBargeIn() when that provider's wire protocol reports an interruption. The zero value is a safe no-op (BargeIn returns nil, SignalBargeIn does nothing); use NewBargeInSignal to enable firing.
func NewBargeInSignal ¶
func NewBargeInSignal() BargeInSignal
NewBargeInSignal returns a BargeInSignal whose channel is ready to fire.
func (BargeInSignal) BargeIn ¶
func (b BargeInSignal) BargeIn() <-chan struct{}
BargeIn returns the out-of-band barge-in channel (nil for the zero value).
func (BargeInSignal) SignalBargeIn ¶
func (b BargeInSignal) SignalBargeIn()
SignalBargeIn delivers one barge-in notification, best-effort and non-blocking: it coalesces if a prior signal is unconsumed, and no-ops on a zero-value (uninitialized) signal. Safe to call from the receive goroutine.
type BaseEmbeddingProvider ¶
type BaseEmbeddingProvider struct {
ProviderModel string
BaseURL string
APIKey string
HTTPClient *http.Client
// Dimensions is the vector length the configured model produces: the
// size the caller declared, else the size of a model the provider knows.
// It is 0 when neither applies, and the provider then takes the length of
// the first vector it gets back rather than guessing one.
Dimensions int
ProviderID string
BatchSize int
// PlatformAuth indicates the HTTPClient's transport applies
// hyperscaler-platform auth (Azure Bearer, etc.) per request, so the
// per-provider empty-API-key guard must be skipped.
PlatformAuth bool
// contains filtered or unexported fields
}
BaseEmbeddingProvider provides common functionality for embedding providers. Embed this struct in provider-specific implementations to reduce duplication.
func NewBaseEmbeddingProvider ¶
func NewBaseEmbeddingProvider( providerID, defaultModel, defaultBaseURL string, defaultDimensions, defaultBatchSize int, defaultTimeout time.Duration, ) *BaseEmbeddingProvider
NewBaseEmbeddingProvider creates a base embedding provider with defaults.
func (*BaseEmbeddingProvider) ApplyHTTPTuning ¶ added in v2.12.0
func (b *BaseEmbeddingProvider) ApplyHTTPTuning(t base.HTTPTuning) error
ApplyHTTPTuning replaces HTTPClient with a tuned copy, implementing base.HTTPTunable for every embedding provider that embeds this struct. A platform-auth transport keeps applying its credential.
func (*BaseEmbeddingProvider) ApplyWiring ¶
func (b *BaseEmbeddingProvider) ApplyWiring(w EmbeddingWiring) (dimsExplicit bool)
ApplyWiring applies the transport-derived settings, leaving each field alone when the wiring does not carry one. It reports whether Dimensions was set, so the caller knows not to overwrite it with a model-family default — a comparison against the default value cannot tell "unset" from "set to the same number".
func (*BaseEmbeddingProvider) CheckDimensions ¶ added in v2.7.0
func (b *BaseEmbeddingProvider) CheckDimensions(embeddings [][]float32) error
CheckDimensions verifies every vector has the length EmbeddingDimensions reports, recording the first length seen when no size is known yet. A mismatch is an error: a caller that sized storage from EmbeddingDimensions would otherwise fail later, far from the cause.
func (*BaseEmbeddingProvider) DoEmbeddingRequest ¶
func (b *BaseEmbeddingProvider) DoEmbeddingRequest( ctx context.Context, cfg HTTPRequestConfig, ) ([]byte, error)
DoEmbeddingRequest performs a common HTTP POST request for embeddings. Returns the response body and any error.
func (*BaseEmbeddingProvider) EmbedWithEmptyCheck ¶
func (b *BaseEmbeddingProvider) EmbedWithEmptyCheck( ctx context.Context, req EmbeddingRequest, embedFn EmbedFunc, ) (EmbeddingResponse, error)
EmbedWithEmptyCheck wraps embedding logic with empty request handling.
func (*BaseEmbeddingProvider) EmbeddingDimensions ¶
func (b *BaseEmbeddingProvider) EmbeddingDimensions() int
EmbeddingDimensions returns the dimensionality of embedding vectors: the declared or known size, else the size observed on the first response, else 0 when neither is available yet.
func (*BaseEmbeddingProvider) EmptyResponseForModel ¶
func (b *BaseEmbeddingProvider) EmptyResponseForModel(model string) EmbeddingResponse
EmptyResponseForModel returns an empty EmbeddingResponse with the given model. Use this for handling empty input cases.
func (*BaseEmbeddingProvider) HandleEmptyRequest ¶
func (b *BaseEmbeddingProvider) HandleEmptyRequest( req EmbeddingRequest, ) (EmbeddingResponse, bool)
HandleEmptyRequest checks if the request has no texts and returns early if so. Returns (response, true) if empty, (zero, false) if not empty.
func (*BaseEmbeddingProvider) ID ¶
func (b *BaseEmbeddingProvider) ID() string
ID returns the provider identifier.
func (*BaseEmbeddingProvider) MaxBatchSize ¶
func (b *BaseEmbeddingProvider) MaxBatchSize() int
MaxBatchSize returns the maximum texts per single API request.
func (*BaseEmbeddingProvider) Model ¶
func (b *BaseEmbeddingProvider) Model() string
Model returns the current embedding model.
func (*BaseEmbeddingProvider) ResolveModel ¶
func (b *BaseEmbeddingProvider) ResolveModel(reqModel string) string
ResolveModel returns the model to use, preferring the request model over the default.
type BaseProvider ¶
type BaseProvider struct {
*base.Implementation
// contains filtered or unexported fields
}
BaseProvider provides common functionality shared across all provider implementations. It should be embedded in concrete provider structs to avoid code duplication.
It carries two distinct HTTP clients: `client` for request/response calls (Predict, embeddings, etc.) which honors the configured request timeout, and `streamingClient` for long-lived SSE streams (PredictStream*) which has Timeout=0 so the client does not impose a wall-clock cap on streams. Liveness for streams is bounded separately by the IdleTimeoutReader wrapping the response body (see StreamIdleTimeout) and by context cancellation from the caller's deadline.
func NewBaseProvider ¶
func NewBaseProvider(id string, includeRawOutput bool, client *http.Client) BaseProvider
NewBaseProvider creates a new BaseProvider with common fields. A companion streaming client is auto-derived from the given client's transport with Timeout=0 so SSE call sites can use GetStreamingHTTPClient() without any extra wiring.
The provider works on a copy of client, so installing its redirect policy (see applyClientPolicies) never changes a client the caller shares, such as http.DefaultClient. The copy keeps client's CheckRedirect and applies it after the provider's own.
func NewBaseProviderWithAPIKey ¶
func NewBaseProviderWithAPIKey( id string, includeRawOutput bool, primaryKey, fallbackKey string, ) (provider BaseProvider, apiKey string)
NewBaseProviderWithAPIKey creates a BaseProvider and retrieves API key from environment It tries the primary key first, then falls back to the secondary key if primary is empty.
func NewBaseProviderWithCredential ¶
func NewBaseProviderWithCredential( id string, includeRawOutput bool, timeout time.Duration, cred Credential, ) (bp BaseProvider, apiKey string)
NewBaseProviderWithCredential creates a BaseProvider with an explicit credential. It creates an HTTP client with the given timeout, builds the BaseProvider, and extracts the API key from the credential (if it is an api_key credential). This eliminates the duplicated credential-setup boilerplate across providers.
The BaseProvider authenticates its requests with cred (see AuthorizeRequest). A provider that sends a different credential, such as the extracted key in its own header, replaces it with SetCredential.
func (*BaseProvider) AcquireStreamSlot ¶
func (b *BaseProvider) AcquireStreamSlot(ctx context.Context) error
AcquireStreamSlot blocks on the configured concurrent-stream semaphore until a slot is available or the context is done. Returns nil on successful acquire (caller MUST call b.ReleaseStreamSlot exactly once) or the context error on cancellation/deadline. Classifies the rejection reason and records it on the promptkit_stream_concurrency_rejections_total counter so operators can see saturation.
With no semaphore configured it returns nil without blocking or emitting metrics, so callers can invoke it unconditionally.
func (*BaseProvider) ApplyCustomHeaders ¶
func (b *BaseProvider) ApplyCustomHeaders(req *http.Request) error
ApplyCustomHeaders applies stored custom headers to the HTTP request. Must be called AFTER the provider sets its own built-in headers (Authorization, Content-Type, etc.) and calls AuthorizeRequest. Returns an error if any custom header collides with a header already set on the request, or with a header the credential sets once the request is sent (case-insensitive per HTTP spec).
func (*BaseProvider) AuthorizeRequest ¶ added in v2.17.0
AuthorizeRequest applies the provider's credential to req while the request is being built; a provider calls it once for each request it builds, before ApplyCustomHeaders. With no rate limit it applies the credential at once, as it always has. Under a rate limit it does nothing: the limiter's transport applies the credential once, after the request's wait ends, so a SigV4 signature or a token is never older than the wait and is computed once per attempt. With no credential it does nothing.
func (*BaseProvider) Close ¶
func (b *BaseProvider) Close() error
Close closes the HTTP client's idle connections
func (*BaseProvider) Credential ¶ added in v2.17.0
func (b *BaseProvider) Credential() Credential
Credential returns the credential the provider authenticates its requests with, or nil when it sends none.
func (*BaseProvider) DoAndReadResponse ¶
func (b *BaseProvider) DoAndReadResponse( req *http.Request, predictResp *PredictionResponse, start time.Time, providerName string, ) (body []byte, statusCode int, err error)
DoAndReadResponse executes an HTTP request using the provider's client, reads the response body (with size limiting), and logs the response. On read error it sets predictResp.Latency. Returns the body bytes and HTTP status code.
func (*BaseProvider) GetHTTPClient ¶
func (b *BaseProvider) GetHTTPClient() *http.Client
GetHTTPClient returns the underlying HTTP client for request/response calls. This client has a finite Timeout (the request_timeout) and MUST NOT be used for SSE streaming. Use GetStreamingHTTPClient for that.
func (*BaseProvider) GetRetryPolicy ¶
func (b *BaseProvider) GetRetryPolicy() pipeline.RetryPolicy
GetRetryPolicy returns the current retry policy.
func (*BaseProvider) GetStreamingHTTPClient ¶
func (b *BaseProvider) GetStreamingHTTPClient() *http.Client
GetStreamingHTTPClient returns a dedicated HTTP client for SSE streaming calls. It shares the non-streaming client's transport but has Timeout=0 so long-lived streams are not killed by a wall-clock cap. When no dedicated streaming client is configured it falls back to the regular client so callers never receive nil.
func (*BaseProvider) HTTPTimeout ¶
func (b *BaseProvider) HTTPTimeout() time.Duration
HTTPTimeout returns the current HTTP client timeout, or 0 if no client is set.
func (*BaseProvider) LoggingContext ¶ added in v2.13.0
LoggingContext returns ctx carrying this provider's ID and model for the logs written during a call.
func (*BaseProvider) MakeJSONRequest ¶
func (b *BaseProvider) MakeJSONRequest( ctx context.Context, url string, request any, headers RequestHeaders, providerName string, ) ([]byte, error)
MakeJSONRequest performs a JSON HTTP POST request with common error handling. This reduces duplication across provider implementations. providerName is used for logging purposes.
func (*BaseProvider) MakeRawRequest ¶
func (b *BaseProvider) MakeRawRequest( ctx context.Context, url string, body []byte, headers RequestHeaders, providerName string, ) ([]byte, error)
MakeRawRequest performs an HTTP POST request with pre-marshaled body. It automatically retries on transient errors (429, 502, 503, 504 and network errors) according to the provider's RetryPolicy. A final status other than 200 returns an error that includes the status code and body.
Custom headers set with SetCustomHeaders are merged into the outgoing request headers up front, with a case-insensitive collision check against the headers the caller passed and the headers the provider's credential sets. A collision fails before the retry loop runs, so it does not consume retries. Each attempt is authorized with the provider's credential (see AuthorizeRequest).
func (*BaseProvider) MaxPayloadSize ¶
func (b *BaseProvider) MaxPayloadSize() int64
MaxPayloadSize returns the current maximum request payload size in bytes.
func (*BaseProvider) MediaLoader ¶
func (b *BaseProvider) MediaLoader() *MediaLoader
MediaLoader returns a new MediaLoader configured with this provider's injected storage service (if any). Providers use it to resolve media parts (ResolveURL for URL-first providers, GetBase64Data for byte-based ones). Each loader counts its own media against MaxMediaItems and MaxAggregateMediaSize, so the built-in providers call it once per message and share the loader across that message's parts: a conversation resends every earlier message, and a loader per request would fail every turn once the history reached a limit.
func (*BaseProvider) ParamRejected ¶ added in v2.13.0
func (b *BaseProvider) ParamRejected(param string) bool
ParamRejected reports whether the API has rejected param for this provider's model. A rejected parameter is not sent.
func (*BaseProvider) ParamSupported ¶ added in v2.13.0
func (b *BaseProvider) ParamSupported(param string) bool
ParamSupported reports whether param may be sent: the config does not list it in unsupported_params, and the API has not rejected it for this model.
func (*BaseProvider) RateLimiter ¶
func (b *BaseProvider) RateLimiter() *rate.Limiter
RateLimiter returns the current rate limiter, or nil if rate limiting is not configured. This is useful for inspecting or sharing limiters.
func (*BaseProvider) RejectedParamNames ¶ added in v2.13.0
func (b *BaseProvider) RejectedParamNames() []string
RejectedParamNames returns the parameters the API has rejected so far.
func (*BaseProvider) ReleaseStreamSlot ¶
func (b *BaseProvider) ReleaseStreamSlot()
ReleaseStreamSlot returns a slot to the concurrent-stream semaphore. Nil-safe; must be paired with a successful AcquireStreamSlot.
func (*BaseProvider) RetryRejectedParams ¶ added in v2.13.0
func (b *BaseProvider) RetryRejectedParams(call func() error) error
RetryRejectedParams runs call, and while it fails because the API rejected a sampling parameter that was still being sent, records the parameter as rejected (so the provider stops sending it, here and on later calls) and runs call again. Each retry follows a newly rejected parameter, so it ends within len(learnableParams) retries. OpenAI names one parameter per 400, which is why it loops.
func (*BaseProvider) RunStreamingRequest ¶
func (b *BaseProvider) RunStreamingRequest( ctx context.Context, req *StreamRetryRequest, consumer StreamConsumer, ) (<-chan StreamChunk, error)
RunStreamingRequest is the entry point streaming-capable providers delegate through. It combines the concurrent-stream semaphore, the retry budget and pre-first-chunk retry with in-flight gauge bookkeeping, so a provider's streaming function supplies only the request and a consumer that parses the provider-specific stream framing.
It:
- Acquires a concurrent-stream slot (blocks on ctx; a nil semaphore is a no-op).
- Increments the streams_in_flight and provider_calls_in_flight gauges.
- Opens the stream with OpenStreamWithRetryRequest and req.
- Starts a goroutine that runs the consumer on the response body and releases the semaphore slot when the consumer returns.
- Starts a relay goroutine that forwards the consumer's chunks to the returned channel, decrements the gauges and closes the channel when the stream ends.
When req.Policy enables StreamRetryWindowAlways and the stream fails after content was forwarded, the relay sends a chunk with Reset set, opens a new stream and forwards that stream's chunks instead, if the retry budget has a token and the context is not canceled.
The relay also gives the final chunk of a stream that ends without an error a *PredictionResponse in FinalResult (unless the provider set one), and reports every chunk to the provider's StreamObserver, if one is installed.
On an error before the goroutines start, it releases the slot and gauges.
Callers must set req.ProviderName to b.ID().
func (*BaseProvider) SetAllowPrivateNetworkMedia ¶ added in v2.13.0
func (b *BaseProvider) SetAllowPrivateNetworkMedia(allow bool)
SetAllowPrivateNetworkMedia lets this provider fetch URL media from non-public addresses. See MediaLoaderConfig.AllowPrivateNetworks for why it is off by default.
func (*BaseProvider) SetCredential ¶ added in v2.17.0
func (b *BaseProvider) SetCredential(cred Credential)
SetCredential sets the credential the provider authenticates its requests with, replacing the one NewBaseProviderWithCredential stored. Nil sends no credential. See AuthorizeRequest.
func (*BaseProvider) SetCustomHeaders ¶
func (b *BaseProvider) SetCustomHeaders(headers map[string]string)
SetCustomHeaders stores custom HTTP headers that will be applied to every outgoing request via ApplyCustomHeaders. Intended for OpenAI-compatible gateway headers (e.g. OpenRouter's HTTP-Referer, X-Title). Called by CreateProviderFromSpec after factory construction.
func (*BaseProvider) SetHTTPTimeout ¶
func (b *BaseProvider) SetHTTPTimeout(timeout time.Duration)
SetHTTPTimeout replaces the request/response HTTP client with a new one that uses the given timeout while preserving the existing transport configuration. Does not affect the streaming client, which remains at Timeout=0.
func (*BaseProvider) SetHTTPTransport ¶
func (b *BaseProvider) SetHTTPTransport(rt http.RoundTripper)
SetHTTPTransport replaces the RoundTripper on both the regular and streaming HTTP clients so the provider routes every outbound request through the supplied transport. Both clients share the transport so connection pooling is effective across request/response and streaming traffic to the same upstream.
CreateProviderFromSpec calls it to apply per-provider connection pool config (see ProviderSpec.HTTPTransport). Provider factories create their client with the default pooled transport and the spec wiring replaces it after construction.
A nil transport resets both clients to Go's http.DefaultTransport via the http.Client zero-value behavior. Passing nil is not the typical use case; callers should build a transport via NewPooledTransportWithOptions and wrap it with NewInstrumentedTransport so the OpenTelemetry span wiring is preserved.
func (*BaseProvider) SetMaxPayloadSize ¶
func (b *BaseProvider) SetMaxPayloadSize(size int64)
SetMaxPayloadSize configures the maximum allowed request payload size in bytes. A zero or negative value disables payload size checking.
func (*BaseProvider) SetMediaStorageService ¶
func (b *BaseProvider) SetMediaStorageService(store storage.MediaStorageService)
SetMediaStorageService injects the media storage service that resolves MediaContent.StorageReference values at request-build time. Nil (the default) disables storage-reference resolution. See MediaStorageConfigurable in registry.go.
func (*BaseProvider) SetRateLimit ¶
func (b *BaseProvider) SetRateLimit(requestsPerSecond float64, burst int)
SetRateLimit configures per-provider rate limiting. requestsPerSecond controls the sustained rate, and burst controls how many requests can be made at once before throttling kicks in; a burst below 1 counts as 1. A zero or negative requestsPerSecond disables rate limiting (the default).
The limit applies to every HTTP request the provider sends through its request/response and streaming clients (Predict, PredictStream, and each retry attempt) by wrapping their transport in a base.RateLimitTransport. A request waits for its turn before it is sent; the wait ends when the request's context is canceled, or at once when its turn falls past the context deadline (base.ErrRateLimitPastDeadline). The wait does not count against the request timeout, which starts when the request is sent. The provider's credential is applied once per attempt, after its wait ends, and to a redirect only when it stays on the same scheme and host (see AuthorizeRequest). CreateProviderFromSpec calls it with spec.RateLimit.
func (*BaseProvider) SetRetryPolicy ¶
func (b *BaseProvider) SetRetryPolicy(policy pipeline.RetryPolicy)
SetRetryPolicy configures the retry policy for this provider.
func (*BaseProvider) SetStreamIdleTimeout ¶
func (b *BaseProvider) SetStreamIdleTimeout(d time.Duration)
SetStreamIdleTimeout configures the SSE body idle timeout. A zero or negative value resets to DefaultStreamIdleTimeout.
func (*BaseProvider) SetStreamObserver ¶ added in v2.17.0
func (b *BaseProvider) SetStreamObserver(o StreamObserver)
SetStreamObserver installs an observer that receives the events of every stream this provider opens through RunStreamingRequest. Nil (the default) observes nothing. See StreamObserver.
func (*BaseProvider) SetStreamRetryBudget ¶
func (b *BaseProvider) SetStreamRetryBudget(budget *RetryBudget)
SetStreamRetryBudget installs a token bucket that rate-limits retry attempts across all in-flight requests on this provider. Passing nil restores unbounded-retry behavior.
func (*BaseProvider) SetStreamRetryPolicy ¶
func (b *BaseProvider) SetStreamRetryPolicy(policy StreamRetryPolicy)
SetStreamRetryPolicy configures bounded retry behavior for the pre-first-chunk streaming window. See StreamRetryPolicy for details.
func (*BaseProvider) SetStreamSemaphore ¶
func (b *BaseProvider) SetStreamSemaphore(sem *StreamSemaphore)
SetStreamSemaphore installs a semaphore that caps concurrent streaming requests. Passing nil restores unlimited concurrency.
func (*BaseProvider) SetUnsupportedParams ¶ added in v2.13.0
func (b *BaseProvider) SetUnsupportedParams(params []string)
SetUnsupportedParams records the parameters the provider config says the model does not take (unsupported_params). Call it while building the provider, before it serves a request.
func (*BaseProvider) ShouldIncludeRawOutput ¶
func (b *BaseProvider) ShouldIncludeRawOutput() bool
ShouldIncludeRawOutput returns whether to include raw API responses in output
func (*BaseProvider) StreamIdleTimeout ¶
func (b *BaseProvider) StreamIdleTimeout() time.Duration
StreamIdleTimeout returns the configured SSE body idle timeout or the package default (DefaultStreamIdleTimeout) when none is set.
func (*BaseProvider) StreamRetryBudget ¶
func (b *BaseProvider) StreamRetryBudget() *RetryBudget
StreamRetryBudget returns the per-provider retry budget. A nil return means retries are unbounded (only MaxAttempts caps them).
func (*BaseProvider) StreamRetryPolicy ¶
func (b *BaseProvider) StreamRetryPolicy() StreamRetryPolicy
StreamRetryPolicy returns the configured streaming-retry policy. The zero value (retry disabled) is the default.
func (*BaseProvider) StreamSemaphore ¶
func (b *BaseProvider) StreamSemaphore() *StreamSemaphore
StreamSemaphore returns the concurrent-stream semaphore. A nil return means unlimited concurrency (backwards-compatible default).
func (*BaseProvider) SupportsStreaming ¶
func (b *BaseProvider) SupportsStreaming() bool
SupportsStreaming returns true by default (can be overridden by providers that don't support streaming)
func (*BaseProvider) WaitForRateLimit ¶
func (b *BaseProvider) WaitForRateLimit(ctx context.Context) error
WaitForRateLimit blocks until the rate limiter allows a request to proceed, or until the context is canceled. If no rate limiter is configured, it returns immediately. Requests sent through the provider's HTTP clients already wait inside their transport, so call it only for outbound work that does not use those clients; each call takes a token.
func (*BaseProvider) WithMedia ¶ added in v2.13.0
func (b *BaseProvider) WithMedia(m MediaSettings) BaseProvider
WithMedia returns a copy of b using m's media settings. A zero field keeps b's own: a nil Storage keeps the store the provider was built with, and AllowPrivateNetworks only ever widens. Providers build their MediaScoped views from it.
type BaseRerankProvider ¶ added in v2.1.0
type BaseRerankProvider struct {
*base.Implementation
ProviderID string
ProviderModel string
BaseURL string
APIKey string
HTTPClient *http.Client
// MaxDocs is the largest candidate list one call accepts.
MaxDocs int
// PlatformAuth indicates the HTTPClient's transport applies
// hyperscaler-platform auth per request, so the empty-API-key guard in
// each vendor's constructor must be skipped.
PlatformAuth bool
}
BaseRerankProvider carries the transport state and lifecycle every hosted reranker needs, so a vendor package only has to describe its wire format. It mirrors BaseEmbeddingProvider, with base.Implementation embedded to satisfy base.Provider (Name/Type/Pricing/Validate/Init/HealthCheck/Close).
func NewBaseRerankProvider ¶ added in v2.1.0
func NewBaseRerankProvider( providerID, defaultModel, defaultBaseURL string, defaultMaxDocs int, defaultTimeout time.Duration, ) *BaseRerankProvider
NewBaseRerankProvider creates a base rerank provider with vendor defaults.
func (*BaseRerankProvider) ApplyHTTPTuning ¶ added in v2.12.0
func (b *BaseRerankProvider) ApplyHTTPTuning(t base.HTTPTuning) error
ApplyHTTPTuning replaces HTTPClient with a tuned copy, implementing base.HTTPTunable for every reranker that embeds this struct.
func (*BaseRerankProvider) DoRerankRequest ¶ added in v2.1.0
func (b *BaseRerankProvider) DoRerankRequest( ctx context.Context, cfg HTTPRequestConfig, ) ([]byte, error)
DoRerankRequest performs the vendor's HTTP call. It shares DoAncillaryJSONRequest with the embedding path so both roles wrap transport failures the same way, which redacts credential-bearing URLs and makes failures classifiable by IsTransient.
func (*BaseRerankProvider) ID ¶ added in v2.1.0
func (b *BaseRerankProvider) ID() string
ID returns the configured provider identifier.
func (*BaseRerankProvider) MaxDocuments ¶ added in v2.1.0
func (b *BaseRerankProvider) MaxDocuments() int
MaxDocuments returns the largest candidate list one call accepts.
func (*BaseRerankProvider) Model ¶ added in v2.1.0
func (b *BaseRerankProvider) Model() string
Model returns the current rerank model.
func (*BaseRerankProvider) RerankWithEmptyCheck ¶ added in v2.1.0
func (b *BaseRerankProvider) RerankWithEmptyCheck( ctx context.Context, req RerankRequest, rerank func(ctx context.Context, req RerankRequest, model string) (RerankResponse, error), ) (RerankResponse, error)
RerankWithEmptyCheck short-circuits the degenerate requests every vendor would otherwise have to guard against, and delegates the rest.
No documents is not an error: it returns an empty result carrying the resolved model. An empty query is an error, as is a document list longer than MaxDocs when MaxDocs is positive.
func (*BaseRerankProvider) ResolveModel ¶ added in v2.1.0
func (b *BaseRerankProvider) ResolveModel(reqModel string) string
ResolveModel returns the per-request model override, or the provider default.
type BedrockEventScanner ¶
type BedrockEventScanner struct {
// contains filtered or unexported fields
}
BedrockEventScanner decodes AWS binary event-stream frames from Bedrock's invoke-with-response-stream endpoint. Each frame's payload is JSON like {"bytes":"<base64>"} where the decoded bytes are a standard Claude JSON event (identical to the SSE data: payloads from the direct API).
func NewBedrockEventScanner ¶
func NewBedrockEventScanner(r io.Reader) *BedrockEventScanner
NewBedrockEventScanner creates a scanner that reads AWS binary event-stream frames.
func (*BedrockEventScanner) Data ¶
func (s *BedrockEventScanner) Data() string
Data returns the decoded Claude JSON event from the last scanned frame.
func (*BedrockEventScanner) Err ¶
func (s *BedrockEventScanner) Err() error
Err returns any error encountered during scanning.
func (*BedrockEventScanner) Scan ¶
func (s *BedrockEventScanner) Scan() bool
Scan reads the next event-stream frame. Returns true if a data event was successfully decoded, false on EOF or error.
type BedrockEventStreamFrameDetector ¶
type BedrockEventStreamFrameDetector struct{}
BedrockEventStreamFrameDetector reads one complete AWS binary event-stream message. The format is:
[4-byte total_length BE][4-byte headers_length BE][4-byte prelude_crc] [headers...][payload...][4-byte message_crc]
The detector reads the 4-byte total_length prefix, then reads exactly (total_length - 4) more bytes to complete the message. This gives the retry driver one full binary frame for replay, confirming the stream is "live" before handing it to the consumer.
Used by the Claude provider when running on AWS Bedrock (Content-Type: application/vnd.amazon.eventstream).
func (BedrockEventStreamFrameDetector) Name ¶
func (BedrockEventStreamFrameDetector) Name() string
Name implements FrameDetector.
func (BedrockEventStreamFrameDetector) PeekFirstFrame ¶
func (BedrockEventStreamFrameDetector) PeekFirstFrame(r io.Reader) ([]byte, error)
PeekFirstFrame reads one complete event-stream message from r and returns the raw bytes. The reader must be positioned at the start of a message boundary.
type ContextWindowProvider ¶
type ContextWindowProvider interface {
MaxContextTokens() int
}
ContextWindowProvider is an optional interface for providers that can report their context window size. The compactor budget is auto-configured from it when a provider implements it and returns a positive value; otherwise the compactor falls back to stage.DefaultBudgetTokens. The openai, claude, gemini and ollama providers implement it.
type Credential ¶
type Credential interface {
// Apply adds authentication to the HTTP request.
Apply(ctx context.Context, req *http.Request) error
// Type returns the credential type identifier.
Type() string
}
Credential applies authentication to HTTP requests. This is the interface that providers use to authenticate requests.
func HeaderKeyCredential ¶ added in v2.17.0
func HeaderKeyCredential(key, header, prefix string) Credential
HeaderKeyCredential returns a credential that sends key in header, after prefix (for example "Bearer "). An empty key returns nil, which sends no credential. Providers that authenticate with a static key use it with SetCredential.
type DoRequestFunc ¶
DoRequestFunc is a function that performs an HTTP request. It is called by DoWithRetry on each attempt.
type EmbeddingProvider ¶
type EmbeddingProvider interface {
// Embed generates embeddings for the given texts.
// The response contains one embedding vector per input text, in the same order.
// Implementations should handle batching internally if the request exceeds MaxBatchSize.
Embed(ctx context.Context, req EmbeddingRequest) (EmbeddingResponse, error)
// EmbeddingDimensions returns the dimensionality of embedding vectors:
// the size configured for the provider, else the known size of its model,
// else the size observed on the first Embed call. It returns 0 when none
// of these is available yet. Embed one text first if you need the size
// before storing vectors.
EmbeddingDimensions() int
// MaxBatchSize returns the maximum number of texts per single API request.
// Callers should batch requests appropriately, or rely on the provider
// to handle splitting internally.
MaxBatchSize() int
// ID returns the provider identifier (e.g., "openai-embedding", "gemini-embedding")
ID() string
}
EmbeddingProvider generates text embeddings for semantic similarity operations. Implementations exist for OpenAI, Gemini, Voyage AI, Hugging Face, Ollama, Bedrock and Vertex AI.
Embeddings are dense vector representations of text that capture semantic meaning. Similar texts will have embeddings with high cosine similarity scores.
Example usage:
provider, err := openai.NewEmbeddingProvider()
if err != nil {
return err
}
resp, err := provider.Embed(ctx, providers.EmbeddingRequest{
Texts: []string{"Hello world", "Hi there"},
})
similarity := stage.CosineSimilarity(resp.Embeddings[0], resp.Embeddings[1])
func CreateEmbeddingProviderFromSpec ¶
func CreateEmbeddingProviderFromSpec(spec EmbeddingProviderSpec) (EmbeddingProvider, error)
CreateEmbeddingProviderFromSpec returns an EmbeddingProvider implementation for the given spec. Like CreateProviderFromSpec for chat providers, it calls the registered factory, then applies spec.Tuning (headers, request timeout, transport) when it is set. It returns an error when no factory is registered for spec.Type, and when Tuning is set for a provider that is not base.HTTPTunable.
type EmbeddingProviderFactory ¶
type EmbeddingProviderFactory func(spec EmbeddingProviderSpec) (EmbeddingProvider, error)
EmbeddingProviderFactory builds an EmbeddingProvider from a spec. Per-provider packages register one of these via init() so the providers package never needs to import them (the implementations already import providers for the interface).
type EmbeddingProviderSpec ¶
type EmbeddingProviderSpec struct {
// ID is a stable identifier; informational only at this layer.
ID string
// Type selects the implementation: openai, gemini, voyageai, ollama,
// huggingface, bedrock or vertex.
Type string
// Model overrides the provider's default embedding model. Empty
// uses the per-provider default.
Model string
// BaseURL overrides the provider's default API endpoint.
BaseURL string
// Credential carries the resolved API key. May be nil for
// providers that don't require auth (e.g. ollama).
Credential credentials.Credential
// AdditionalConfig carries provider-specific extras (voyage
// dimensions/input_type, etc.). Unknown keys are ignored.
AdditionalConfig map[string]any
// Platform identifies the hosting platform ("azure", "bedrock",
// "vertex"). Empty means direct API access via Credential. Mirrors
// ProviderSpec.Platform on the chat path.
Platform string
// PlatformConfig holds platform-specific settings (endpoint, region,
// api_version). Only set when Platform != "".
PlatformConfig *PlatformConfig
// Tuning carries the provider file's headers, request_timeout and
// http_transport. CreateEmbeddingProviderFromSpec applies it after
// construction and rejects it for a provider that is not HTTPTunable.
Tuning base.HTTPTuning
}
EmbeddingProviderSpec is the runtime form of an embedding-provider declaration, used by CreateEmbeddingProviderFromSpec to construct an EmbeddingProvider implementation. The SDK's runtime-config layer translates pkg/config.EmbeddingProviderConfig into this struct after resolving credentials.
type EmbeddingRequest ¶
type EmbeddingRequest struct {
// Texts to embed (batched for efficiency)
Texts []string
// Model override for embedding model (optional, uses provider default if empty)
Model string
}
EmbeddingRequest represents a request for text embeddings.
type EmbeddingResponse ¶
type EmbeddingResponse struct {
// Embeddings contains one vector per input text, in the same order
Embeddings [][]float32
// Model is the model that was used for embedding
Model string
// Usage contains token consumption information (optional)
Usage *EmbeddingUsage
}
EmbeddingResponse contains the embedding vectors from a provider.
type EmbeddingTransport ¶
type EmbeddingTransport struct {
Client *http.Client
BaseURL string
APIKey string
PlatformAuth bool
}
EmbeddingTransport is the resolved HTTP wiring for a vendor embedding factory. Exactly one of the two modes is populated:
- static key: Client==nil, PlatformAuth==false, APIKey may be set
- platform: Client!=nil, PlatformAuth==true, APIKey==""
BaseURL is the platform-resolved endpoint, or the spec's BaseURL override, or "" (provider keeps its built-in default).
func ResolveEmbeddingTransport ¶
func ResolveEmbeddingTransport(spec EmbeddingProviderSpec) (EmbeddingTransport, error)
ResolveEmbeddingTransport decides between the static-API-key path and a hyperscaler-platform path for an embedding provider, mirroring the chat path's credential and platform handling. With no spec.Platform it returns the spec's BaseURL and API key. With a platform (azure, bedrock or vertex) it returns an HTTP client that applies the credential per request and the platform's endpoint, or an error when the provider type or platform settings do not fit.
type EmbeddingUsage ¶
type EmbeddingUsage struct {
// TotalTokens is the total number of tokens processed
TotalTokens int
}
EmbeddingUsage tracks token consumption for embedding requests.
type EmbeddingWiring ¶
type EmbeddingWiring struct {
Model string
BaseURL string
Client *http.Client
PlatformAuth bool
// Dimensions is 0 when the spec did not request one, which is what tells
// the provider to keep its family default.
Dimensions int
}
EmbeddingWiring is the transport-derived configuration every platform-native embedding provider applies the same way. Family-specific settings (Cohere's input_type, Vertex's task_type) stay with their own provider.
func EmbeddingWiringFrom ¶
func EmbeddingWiringFrom(spec EmbeddingProviderSpec, tr EmbeddingTransport) EmbeddingWiring
EmbeddingWiringFrom extracts the shared wiring from a spec and its resolved transport.
type ExecutionResult ¶
type ExecutionResult interface{}
ExecutionResult is the complete result a stream's final chunk carries in StreamChunk.FinalResult. It is an empty interface so this package need not import the layers above it. A provider stream run through BaseProvider.RunStreamingRequest ends with a *PredictionResponse; the SDK's session stream ends with a *pipeline.ExecutionResult.
type FrameDetector ¶
type FrameDetector interface {
// Name identifies the detector in logs and errors. Should be a
// short lowercase token: "sse", "ndjson", "json-array", etc.
Name() string
// PeekFirstFrame reads from r until at least one complete frame has
// been seen, then returns the bytes consumed so far. Returns an
// error if r fails before a complete frame is found, or if the
// stream ends cleanly before any frame has been observed.
//
// On success, the returned slice is non-empty and r is positioned
// immediately after the last returned byte.
PeekFirstFrame(r io.Reader) ([]byte, error)
}
FrameDetector extracts the bytes of the first complete "frame" from a streaming response body. The concept of a frame is protocol-specific: SSE uses `data: ...\n\n` boundaries, NDJSON uses line terminators, Gemini's JSON-array streaming uses balanced-brace JSON objects inside a top-level array.
The returned bytes MUST be exactly a prefix of the underlying stream: the detector reads from r, returns everything it has consumed so far, and leaves r positioned immediately after the returned bytes. This is what lets the retry driver wrap the returned bytes + remaining body in a replayReadCloser so downstream parsers see a contiguous stream.
Detectors MUST drain any internal bufio lookahead into the returned slice before returning — if they use a bufio.Reader for efficiency, bytes buffered past the frame boundary belong in the replay slice, not stuck in a throwaway bufio buffer.
Detectors SHOULD NOT wrap r with an idle-timeout reader themselves; the retry driver applies the caller's StreamIdleTimeout to r before handing it to the detector, so each detector gets uniform idle protection for free.
type HTTPRequestConfig ¶
type HTTPRequestConfig struct {
URL string
Body []byte
UseAPIKey bool // If true, adds Authorization: Bearer <APIKey> header
ContentType string // Defaults to application/json
// Headers are set on the request before it is sent. Providers that
// authenticate with a non-Bearer scheme use this, notably Gemini, whose
// key goes in x-goog-api-key so it never enters the URL and therefore
// never reaches a log through *url.Error.
Headers map[string]string
}
HTTPRequestConfig configures how to make an HTTP request.
type HTTPTransportOptions ¶
type HTTPTransportOptions struct {
// MaxConnsPerHost caps the total TCP connections the transport may
// open to any single host (in-use + idle). Zero means unlimited
// (matching Go's http.Transport default). Negative values fall
// back to DefaultMaxConnsPerHost.
MaxConnsPerHost int
// MaxIdleConnsPerHost caps the number of idle keep-alive
// connections the transport will retain per host for reuse. Zero
// uses DefaultMaxIdleConnsPerHost. Usually tracked to
// MaxConnsPerHost to keep the whole pool reusable.
MaxIdleConnsPerHost int
// IdleConnTimeout is how long an idle keep-alive connection lingers
// before being closed. Zero uses DefaultIdleConnTimeout. Longer
// timeouts favor reuse; shorter ones release memory and FD slots
// faster.
IdleConnTimeout time.Duration
}
HTTPTransportOptions configures the connection pool for a pooled HTTP transport. A zero MaxConnsPerHost means unlimited (matching Go's http.Transport); a zero MaxIdleConnsPerHost or IdleConnTimeout falls back to its package default (DefaultMaxIdleConnsPerHost, DefaultIdleConnTimeout).
These are the single-process pool controls that bound how many concurrent streams a provider can multiplex to one upstream host. Together with the upstream's advertised SETTINGS_MAX_CONCURRENT_STREAMS (RFC 7540 section 6.5.2), MaxConnsPerHost sets the steady-state ceiling for concurrent streams per process.
type IdleTimeoutReader ¶
type IdleTimeoutReader struct {
// contains filtered or unexported fields
}
IdleTimeoutReader wraps an io.ReadCloser with idle timeout detection. If no data is read within the configured timeout, the underlying reader is closed, causing any blocking Read to return an error.
func NewIdleTimeoutReader ¶
func NewIdleTimeoutReader(r io.ReadCloser, timeout time.Duration) *IdleTimeoutReader
NewIdleTimeoutReader wraps the given reader with idle timeout detection. The timeout is reset on every successful Read that returns data. If the timeout fires, the underlying reader is closed to unblock any pending Read calls.
func (*IdleTimeoutReader) Close ¶
func (r *IdleTimeoutReader) Close() error
Close stops the idle timer and closes the underlying reader.
func (*IdleTimeoutReader) Read ¶
func (r *IdleTimeoutReader) Read(p []byte) (int, error)
Read reads from the underlying reader and resets the idle timer on success. If the idle timer fired and closed the underlying reader, the resulting read error is reported as ErrStreamIdleTimeout so callers can distinguish a deliberate idle abort from a transient network drop.
type ImageDetail ¶
type ImageDetail string
ImageDetail specifies the level of detail for image processing
const ( ImageDetailLow ImageDetail = "low" // Faster, less detailed analysis ImageDetailHigh ImageDetail = "high" // Slower, more detailed analysis ImageDetailAuto ImageDetail = "auto" // Provider chooses automatically )
Image detail levels for multimodal processing.
type InferenceProvider ¶
type InferenceProvider = Provider
InferenceProvider is the unified name for predict-based LLM providers. Provider remains as a deprecated alias for back-compat with existing call sites.
func AssertInferenceProvider ¶
func AssertInferenceProvider(p base.Provider) (InferenceProvider, error)
AssertInferenceProvider type-asserts a base.Provider as an InferenceProvider. Returns an error if the provider is not an inference provider.
type JSONArrayFrameDetector ¶
type JSONArrayFrameDetector struct{}
JSONArrayFrameDetector detects the first complete top-level object inside a streaming JSON array. This is the framing used by Gemini's `streamGenerateContent` endpoint, which returns
[
{"candidates": [...], "usageMetadata": {...}},
{"candidates": [...], "usageMetadata": {...}},
...
]
parsed incrementally by a downstream `json.Decoder`. The detector reads past leading whitespace and the opening `[`, then scans bytes until it finds the end of the first `{...}` at depth 0 (respecting JSON string escapes).
The detector parses at byte level because a `json.Decoder` would work but it buffers aggressively and makes it harder to track exactly how many bytes have been consumed from the underlying reader.
On success the returned bytes form a prefix of the stream ending at the closing brace of the first object. The downstream `json.Decoder` continues from there and expects either `,` or `]` next, and that is what remains in the stream.
func (JSONArrayFrameDetector) Name ¶
func (JSONArrayFrameDetector) Name() string
Name implements FrameDetector.
func (JSONArrayFrameDetector) PeekFirstFrame ¶
func (JSONArrayFrameDetector) PeekFirstFrame(r io.Reader) ([]byte, error)
PeekFirstFrame reads bytes from r tracking JSON state until the first top-level object inside the array is complete.
type JitterHealthReporter ¶
type JitterHealthReporter struct {
// contains filtered or unexported fields
}
JitterHealthReporter forwards the DELTAS of a jitter buffer's cumulative underrun/drop counters to StreamMetrics. A realtime audio consumer keeps one per buffer and calls Report once per pull/tick; it remembers the last-seen cumulative values so repeated calls never double-count.
It connects a realtime audio consumer to the off-bus StreamMetrics layer. The zero value is ready to use. It is not safe for concurrent use: call Report from the single consumer goroutine.
func (*JitterHealthReporter) Report ¶
func (r *JitterHealthReporter) Report(m *StreamMetrics, jb jitterHealthCounters, direction string)
Report emits the counter deltas since the last call to m (nil-safe) for the given direction ("input"/"output"). jb is the live jitter buffer. This is a DIRECT-UPDATE path: it never publishes to the event bus (see the off-bus invariant on StreamMetrics).
type LateInputTranscriber ¶
type LateInputTranscriber interface {
// EmitsLateInputTranscription reports whether the user transcript can arrive
// after the assistant reply has started for the same turn.
EmitsLateInputTranscription() bool
}
LateInputTranscriber is an optional interface a StreamInputSupport provider implements to declare that it delivers the user's input transcription AFTER the assistant response has already begun — e.g. OpenAI Realtime, whose Whisper transcription arrives asynchronously, after the model has started replying.
When a provider reports true (and input transcription is enabled), the streaming pipeline reorders the transcript so each turn's user text precedes its assistant text. Providers that emit the transcript before the reply (or not at all) need not implement this — reordering stays off by default.
type MediaLoader ¶
type MediaLoader struct {
// contains filtered or unexported fields
}
MediaLoader handles loading media content from various sources (inline data, files, URLs, storage). It provides a unified interface for providers to access media regardless of the source. A loader counts what it loads against MaxMediaItems and MaxAggregateMediaSize, so share one loader across everything the limits should cover. MediaLoader is not safe for concurrent use.
func NewMediaLoader ¶
func NewMediaLoader(config MediaLoaderConfig) *MediaLoader
NewMediaLoader creates a new MediaLoader with the given configuration.
func (*MediaLoader) GetBase64Data ¶
func (ml *MediaLoader) GetBase64Data(ctx context.Context, media *types.MediaContent) (string, error)
GetBase64Data loads media content and returns it as base64-encoded data. It handles all media sources: inline data, file paths, URLs, and storage references. It enforces per-item size limits, aggregate size limits, and item count limits.
Example ¶
ExampleMediaLoader_GetBase64Data shows loading inline base64 media data via a MediaLoader. Inline data is returned as-is with no file or network access, so this example needs no external resources or credentials.
package main
import (
"context"
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/providers"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
loader := providers.NewMediaLoader(providers.MediaLoaderConfig{})
data := "aGVsbG8=" // base64 for "hello"
media := &types.MediaContent{Data: &data, MIMEType: "text/plain"}
encoded, err := loader.GetBase64Data(context.Background(), media)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(encoded)
}
Output: aGVsbG8=
func (*MediaLoader) ResolveURL ¶
func (ml *MediaLoader) ResolveURL(ctx context.Context, media *types.MediaContent) (string, bool, error)
ResolveURL returns a URL a provider can hand to the model when the media can be represented as one. ok is false when the source cannot be a fetchable URL (inline data, local file path, a non-remote storage URL such as file://, or a storage reference with no store configured); callers then fall back to GetBase64Data. The loader passes an expiry of 0 to the store, so the store chooses its own URL expiry policy.
type MediaLoaderConfig ¶
type MediaLoaderConfig struct {
// StorageService is optional - required only for loading from storage references
StorageService storage.MediaStorageService
// HTTPTimeout for URL fetching (default: 30s)
HTTPTimeout time.Duration
// MaxURLSizeBytes is the maximum size for URL-based media and for a local
// file (default: 50MB)
MaxURLSizeBytes int64
// AllowPrivateNetworks lets URL media be fetched from loopback, private,
// link-local and other non-public addresses. Off by default, and it should
// stay off: a media URL can come from a remote client or a model, and
// fetching it from the host is how such a URL reaches the host's cloud
// metadata service or internal network. Turn it on only when every media
// URL comes from a source the host trusts.
AllowPrivateNetworks bool
}
MediaLoaderConfig configures the MediaLoader behavior.
type MediaScoped ¶ added in v2.13.0
type MediaScoped interface {
WithMediaSettings(MediaSettings) Provider
}
MediaScoped is implemented by a provider that can give one conversation a view of itself with that conversation's MediaSettings. The view shares the provider's clients and state; only the media settings differ, so a host that shares one provider across conversations keeps each one's store and network policy its own. Setting them on the shared provider (MediaStorageConfigurable) lets the last conversation opened decide for all.
type MediaSettings ¶ added in v2.13.0
type MediaSettings struct {
Storage storage.MediaStorageService
AllowPrivateNetworks bool
}
MediaSettings are the media options one conversation applies: the store that resolves storage references, and whether URL media may be fetched from non-public addresses. A zero field keeps the provider's own setting.
type MediaStorageConfigurable ¶
type MediaStorageConfigurable interface {
SetMediaStorageService(storage.MediaStorageService)
}
MediaStorageConfigurable is implemented by any provider embedding *BaseProvider. CreateProviderFromSpec uses it to inject the media storage service so providers can resolve MediaContent.StorageReference values at request-build time.
NOSONAR: name intentionally matches the existing *Configurable pattern for post-construction wiring interfaces (timeoutConfigurable etc.)
type MessageMetadataTemplater ¶ added in v2.14.0
type MessageMetadataTemplater interface {
MessageMetadataTemplate() string
}
MessageMetadataTemplater is implemented by a provider that renders a message's application metadata (types.Message.Metadata) for the model. The provider stage fills the template's {{key}} placeholders from each message's metadata and appends the result to that message's text in the request only. An empty template means the model does not see the metadata. ProviderSpec.MessageMetadataTemplate sets it.
type MockRerankOption ¶ added in v2.1.0
type MockRerankOption func(*MockRerankProvider)
MockRerankOption configures a MockRerankProvider.
func WithMockRerankHandler ¶ added in v2.1.0
func WithMockRerankHandler( h func(ctx context.Context, req RerankRequest) (RerankResponse, error), ) MockRerankOption
WithMockRerankHandler installs a handler that replaces the built-in scoring.
func WithMockRerankID ¶ added in v2.1.0
func WithMockRerankID(id string) MockRerankOption
WithMockRerankID sets the provider's reported ID.
func WithMockRerankMaxDocuments ¶ added in v2.1.0
func WithMockRerankMaxDocuments(n int) MockRerankOption
WithMockRerankMaxDocuments sets the reported document cap, so a test can exercise a caller's batching without sending a thousand documents.
type MockRerankProvider ¶ added in v2.1.0
type MockRerankProvider struct {
*base.Implementation
// Handler, when set, replaces the built-in scoring entirely. Use it to
// pin an exact order, or to make the provider fail, without standing up
// an HTTP server.
Handler func(ctx context.Context, req RerankRequest) (RerankResponse, error)
// contains filtered or unexported fields
}
MockRerankProvider ranks without a network call, for tests and local development.
It scores by counting how many of the query's whitespace-separated terms appear in each document, case-insensitively. The scoring is crude but predictable, so a test can assert an exact order without pinning a vendor model's behavior. Ties keep the input order, so the result is deterministic.
Scores are matched terms over query terms, from 0 to 1. They are not comparable to a hosted provider's scores.
func NewMockRerankProvider ¶ added in v2.1.0
func NewMockRerankProvider(opts ...MockRerankOption) *MockRerankProvider
NewMockRerankProvider creates an in-process rerank provider.
func (*MockRerankProvider) ID ¶ added in v2.1.0
func (p *MockRerankProvider) ID() string
ID returns the provider identifier.
func (*MockRerankProvider) MaxDocuments ¶ added in v2.1.0
func (p *MockRerankProvider) MaxDocuments() int
MaxDocuments returns the configured document cap.
func (*MockRerankProvider) Rerank ¶ added in v2.1.0
func (p *MockRerankProvider) Rerank( ctx context.Context, req RerankRequest, ) (RerankResponse, error)
Rerank orders documents by term overlap with the query.
type MultimodalCapabilities ¶
type MultimodalCapabilities struct {
SupportsImages bool // Provider can process image inputs
SupportsAudio bool // Provider can process audio inputs
SupportsVideo bool // Provider can process video inputs
SupportsDocuments bool // Provider can process document inputs (PDF, etc.)
ImageFormats []string // Supported image MIME types (e.g., "image/jpeg", "image/png")
AudioFormats []string // Supported audio MIME types (e.g., "audio/mpeg", "audio/wav")
VideoFormats []string // Supported video MIME types (e.g., "video/mp4")
DocumentFormats []string // Supported document MIME types (e.g., "application/pdf")
MaxImageSizeMB int // Maximum image size in megabytes (0 = unlimited/unknown)
MaxAudioSizeMB int // Maximum audio size in megabytes (0 = unlimited/unknown)
MaxVideoSizeMB int // Maximum video size in megabytes (0 = unlimited/unknown)
MaxDocumentSizeMB int // Maximum document size in megabytes (0 = unlimited/unknown)
}
MultimodalCapabilities describes what types of multimodal content a provider supports
func ApplyDeclaredModalities ¶ added in v2.17.0
func ApplyDeclaredModalities(caps MultimodalCapabilities, declared map[string]bool) MultimodalCapabilities
ApplyDeclaredModalities returns caps with each modality switch set from the declared capability set. A nil set means the provider config declares nothing, so caps is returned unchanged.
type MultimodalCapabilityProvider ¶
type MultimodalCapabilityProvider interface {
GetMultimodalCapabilities() MultimodalCapabilities
}
MultimodalCapabilityProvider is implemented by providers that support multimodal content.
func GetMultimodalProvider ¶
func GetMultimodalProvider(p Provider) MultimodalCapabilityProvider
GetMultimodalProvider safely casts a provider to MultimodalCapabilityProvider Returns nil if the provider doesn't support multimodal
type NDJSONFrameDetector ¶
type NDJSONFrameDetector struct{}
NDJSONFrameDetector detects newline-delimited JSON frames. Each frame is one complete JSON object terminated by a literal `\n`, as in Ollama's native streaming API (`{"response":"..."}\n`) and other non-SSE APIs that stream raw JSON. A provider streaming such an API sets it as StreamRetryRequest.FrameDetector when it calls RunStreamingRequest. The built-in providers all stream SSE or a JSON array (PromptKit's Ollama provider uses the OpenAI-compatible SSE endpoint), so none of them uses it.
This detector does NOT validate that the line is parseable JSON; it only looks for the line terminator. Upstream producers that emit partial JSON would fail at the downstream parser, not here. This matches the SSE detector's behavior of not interpreting the payload.
func (NDJSONFrameDetector) Name ¶
func (NDJSONFrameDetector) Name() string
Name implements FrameDetector.
func (NDJSONFrameDetector) PeekFirstFrame ¶
func (NDJSONFrameDetector) PeekFirstFrame(r io.Reader) ([]byte, error)
PeekFirstFrame reads until the first `\n` and returns the line (including the newline) plus any bufio lookahead. Blank lines are skipped so leading whitespace or keepalive newlines from certain producers don't count as a "frame".
type PlatformConfig ¶
type PlatformConfig = credentials.PlatformConfig
PlatformConfig is an alias for credentials.PlatformConfig.
type PlatformEmbeddingSpec ¶
type PlatformEmbeddingSpec struct {
// PlatformHint completes the "requires a platform block (…)" error, naming
// the fields that platform actually needs.
PlatformHint string
// Build constructs the provider once the transport has been resolved.
Build func(EmbeddingProviderSpec, EmbeddingTransport) (EmbeddingProvider, error)
}
PlatformEmbeddingSpec describes a platform-native embedding provider: one whose request bodies are the cloud's own rather than OpenAI-shaped, so it is selected by provider type and cannot be hosted on the OpenAI path.
type PredictionRequest ¶
type PredictionRequest struct {
System string `json:"system"`
Messages []types.Message `json:"messages"`
Temperature float32 `json:"temperature"`
// TemperatureSet marks Temperature as set explicitly, so a zero is sent
// as zero instead of being replaced by the provider's default temperature
// (see ResolveTemperature).
TemperatureSet bool `json:"temperature_set,omitempty"`
TopP float32 `json:"top_p"`
MaxTokens int `json:"max_tokens"`
// FrequencyPenalty and PresencePenalty are sent by providers whose API
// takes them; nil sends nothing.
FrequencyPenalty *float32 `json:"frequency_penalty,omitempty"`
PresencePenalty *float32 `json:"presence_penalty,omitempty"`
// TopK limits sampling to the K most likely tokens; nil sends nothing.
// A provider whose API takes no top_k, or no penalties, drops them and
// says so with WarnUnsentParams.
TopK *int `json:"top_k,omitempty"`
Seed *int `json:"seed,omitempty"`
ResponseFormat *ResponseFormat `json:"response_format,omitempty"` // Optional response format (JSON mode)
Metadata map[string]any `json:"metadata,omitempty"` // Provider-specific context
}
PredictionRequest represents a request to a predict provider
func (*PredictionRequest) NormalizeMessages ¶
func (r *PredictionRequest) NormalizeMessages()
NormalizeMessages extracts system-role messages from Messages, merges their content into the System field, and removes them from Messages. This ensures all providers receive system context through the dedicated System field rather than as role entries that some providers silently drop.
Ordering: existing System content first, then system-role message content in original order, separated by double newlines.
This method is idempotent: calling it on an already-normalized request (no system-role messages in Messages) is a no-op.
type PredictionResponse ¶
type PredictionResponse struct {
Content string `json:"content"`
Parts []types.ContentPart `json:"parts,omitempty"` // Multimodal content parts (text, image, audio, video)
CostInfo *types.CostInfo `json:"cost_info,omitempty"` // Cost breakdown (includes token counts)
Latency time.Duration `json:"latency"`
Raw []byte `json:"raw,omitempty"`
RawRequest any `json:"raw_request,omitempty"` // Raw API request (for debugging)
ToolCalls []types.MessageToolCall `json:"tool_calls,omitempty"` // Tools called in this response
// Reasoning holds the model's reasoning/"thinking" for this response, carried
// onto Message.Reasoning (off Parts) so it is excluded from content/exports/
// future context by construction. Nil when the model reported none.
Reasoning *types.ReasoningTrace `json:"reasoning,omitempty"`
// FinishReason is the canonical (normalized) reason the model stopped,
// or "" if the provider did not report one. See runtime/types FinishReason* constants.
FinishReason string `json:"finish_reason,omitempty"`
}
PredictionResponse represents a response from a predict provider
func RetryToolCall ¶ added in v2.13.0
func RetryToolCall( b *BaseProvider, req PredictionRequest, call func(PredictionRequest) (PredictionResponse, []types.MessageToolCall, error), ) (PredictionResponse, []types.MessageToolCall, error)
RetryToolCall is RetryCall for PredictWithTools, which also returns the tool calls.
type Pricing ¶
Pricing holds flat cost-per-1K-token rates for input and output. When both are positive they take precedence over a provider's built-in per-model price table, which serves as a fallback and is not an authoritative price list.
type PrivateNetworkMediaConfigurable ¶ added in v2.13.0
type PrivateNetworkMediaConfigurable interface {
SetAllowPrivateNetworkMedia(allow bool)
}
PrivateNetworkMediaConfigurable is implemented by any provider embedding *BaseProvider. It lets a host that trusts every media URL it passes allow fetching them from non-public addresses; see MediaLoaderConfig.AllowPrivateNetworks.
type Provider ¶
type Provider interface {
base.Provider // adds Name, Type, Pricing, Validate, Init, HealthCheck, Close
// ID returns the provider ID. It is an alias for Name.
ID() string
// Model returns the model name/identifier used by this provider.
Model() string
Predict(ctx context.Context, req PredictionRequest) (PredictionResponse, error)
// Streaming support
PredictStream(ctx context.Context, req PredictionRequest) (<-chan StreamChunk, error)
SupportsStreaming() bool
ShouldIncludeRawOutput() bool
// CalculateCost calculates cost breakdown for given token counts.
CalculateCost(inputTokens, outputTokens, cachedTokens int) types.CostInfo
}
Provider interface defines the contract for predict providers. It embeds base.Provider for cross-cutting concerns (identity, lifecycle, pricing) and adds inference-specific operations.
func CreateProviderFromSpec ¶
func CreateProviderFromSpec(spec ProviderSpec) (Provider, error)
CreateProviderFromSpec creates a provider implementation from a spec. It fills in spec.BaseURL with the type's default (OpenAI, Gemini, Claude, Ollama and vLLM have one) when it is empty, calls the factory registered for spec.Type, then applies the spec's timeouts, stream retry and concurrency settings, stream observer, HTTP transport, rate limit, custom headers, media storage and message metadata template to the provider. It returns an UnsupportedProviderError when no factory is registered for spec.Type.
type ProviderContractTests ¶
type ProviderContractTests struct {
// Provider instance to test
Provider Provider
// SupportsToolsExpected indicates whether this provider should support tools
SupportsToolsExpected bool
// SupportsStreamingExpected indicates whether this provider should support streaming
SupportsStreamingExpected bool
}
ProviderContractTests defines a comprehensive test suite that validates the Provider interface contract. All provider implementations should pass these tests to ensure consistent behavior across the system.
Usage:
func TestOpenAIProviderContract(t *testing.T) {
provider := NewProvider(...)
providers.RunProviderContractTests(t, providers.ProviderContractTests{
Provider: provider,
SupportsToolsExpected: true,
SupportsStreamingExpected: true,
})
}
type ProviderDefaults ¶
type ProviderDefaults struct {
Temperature float32
TopP float32
MaxTokens int
Pricing Pricing
// DisablePromptCaching, when true, disables Anthropic prompt caching.
// Default (false) means caching is on for all models that support it.
DisablePromptCaching bool
}
ProviderDefaults holds default parameters for providers.
Each applies only when the request leaves the field at zero; a positive request value always wins. A MaxTokens of zero or MaxTokensUnlimited sends no output-token limit, except on Claude, where zero falls back to 4096.
Example ¶
ExampleProviderDefaults shows the defaults passed to every provider constructor.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/providers"
)
func main() {
d := providers.ProviderDefaults{Temperature: 0.7, MaxTokens: 2000}
fmt.Printf("temp=%.1f max=%d\n", d.Temperature, d.MaxTokens)
}
Output: temp=0.7 max=2000
type ProviderFactory ¶
type ProviderFactory func(spec ProviderSpec) (Provider, error)
ProviderFactory is a function that creates a provider from a spec
func CredentialFactory ¶
func CredentialFactory(withCred, withoutCred ProviderFactory) ProviderFactory
CredentialFactory builds a ProviderFactory that calls withCred when the spec has a credential (HasCredential) and withoutCred otherwise.
Example, in a provider's init():
providers.RegisterProviderFactory("claude", providers.CredentialFactory(
func(spec providers.ProviderSpec) (providers.Provider, error) {
return NewToolProviderWithCredential(spec.ID, spec.Model, ..., spec.Credential, ...), nil
},
func(spec providers.ProviderSpec) (providers.Provider, error) {
return NewToolProvider(spec.ID, spec.Model, ...), nil
},
))
func RejectPlatforms ¶
func RejectPlatforms(rejected map[string]bool, inner ProviderFactory) ProviderFactory
RejectPlatforms wraps a ProviderFactory so it returns an UnsupportedProviderPlatformError when spec.Platform is in rejected. Per-provider init() functions use it to fail fast on (provider, platform) pairs the underlying vendor does not host.
type ProviderHTTPError ¶
type ProviderHTTPError struct {
StatusCode int
URL string
Body string
Provider string
// RetryAfter is the delay the response's Retry-After header asked for,
// or zero when it sent none.
RetryAfter time.Duration
}
ProviderHTTPError wraps a non-2xx HTTP response from a provider API. Use errors.As to extract the status code for classification.
func (*ProviderHTTPError) Error ¶
func (e *ProviderHTTPError) Error() string
Error redacts credential-bearing query parameters in the URL. Some providers authenticate via the query string, so an unredacted URL in an error message writes a live credential to every log that touches it.
type ProviderSpec ¶
type ProviderSpec struct {
ID string
Type string
Model string
BaseURL string
// Headers contains custom HTTP headers to include in every request.
// A header that collides with one the provider sets itself (compared
// case-insensitively) makes the request fail with an error.
Headers map[string]string
Defaults ProviderDefaults
IncludeRawOutput bool
AdditionalConfig map[string]interface{} // Flexible key-value pairs for provider-specific configuration
// Credential holds the resolved credential for this provider.
// If nil, providers fall back to environment variable lookup.
Credential Credential
// Platform identifies the hosting platform (e.g., "bedrock", "vertex", "azure").
// Empty string means direct API access to the provider.
Platform string
// PlatformConfig holds platform-specific configuration.
// Only set when Platform is non-empty.
PlatformConfig *PlatformConfig
// UnsupportedParams lists sampling parameters the model does not take
// (for example "temperature" or "top_p"). The provider does not send them.
UnsupportedParams []string
// Capabilities lists the modalities/features the configured model supports
// (e.g. "text", "vision", "audio", "video", "tools", "json"). When set, it
// is the source of truth for multimodal support, replacing per-model
// hardcoding inside providers. Empty means "not declared", and providers
// fall back to their built-in defaults.
Capabilities []string
// RequestTimeout caps the wall-clock duration of request/response HTTP
// calls (Predict, embeddings). Zero keeps the provider's default timeout.
// Does not apply to SSE streaming calls, which are unbounded by wall-clock
// and governed by StreamIdleTimeout and context cancellation.
RequestTimeout time.Duration
// StreamIdleTimeout bounds how long an SSE streaming body may remain
// silent before it is aborted; the timer resets on every read that returns
// data. Zero falls back to DefaultStreamIdleTimeout.
StreamIdleTimeout time.Duration
// StreamRetry configures bounded retry for streaming requests that
// fail in the pre-first-chunk window. The zero value (disabled) leaves
// the provider with no streaming retry.
StreamRetry StreamRetryPolicy
// StreamRetryBudget is a pre-constructed token bucket that
// rate-limits retry attempts across all in-flight requests on this
// provider. Nil means unbounded retries (only MaxAttempts caps them).
// It is applied only when StreamRetry.Enabled is true. Each provider
// instance gets its own budget, so one misbehaving model cannot starve
// retry capacity for others.
StreamRetryBudget *RetryBudget
// StreamMaxConcurrent caps the number of concurrent streaming
// requests the provider will have in flight. Zero means unlimited. It is
// applied through SetStreamSemaphore on providers that embed BaseProvider.
StreamMaxConcurrent int
// StreamObserver receives the events of every stream the provider opens
// (see StreamObserver). It is applied through SetStreamObserver on
// providers that embed BaseProvider. Nil observes nothing.
StreamObserver StreamObserver
// StorageService resolves MediaContent.StorageReference values at
// request-build time (to a model-fetchable URL via GetURL, or bytes via
// RetrieveMedia). It is applied through SetMediaStorageService on providers
// implementing MediaStorageConfigurable. Nil disables storage references.
StorageService storage.MediaStorageService
// HTTPTransport configures the per-provider HTTP connection pool.
// Zero-valued fields fall back to package-level defaults
// (DefaultMaxConnsPerHost, etc.). It is applied through SetHTTPTransport on
// providers that embed BaseProvider, replacing the default pooled
// transport the factory constructed. MaxConnsPerHost, together with the
// upstream's SETTINGS_MAX_CONCURRENT_STREAMS, bounds the concurrent
// streams one process can hold open to a host.
HTTPTransport HTTPTransportOptions
// RateLimit caps how fast this provider instance sends requests (see
// RateLimitOptions). The zero value is unlimited. It is applied through
// SetRateLimit on providers that embed BaseProvider.
RateLimit RateLimitOptions
// MessageMetadataTemplate renders a message's application metadata
// (types.Message.Metadata, set with the SDK's WithMessageMetadata) as
// text the model reads. Its {{key}} placeholders are filled from each
// message's metadata, and the result is appended to that message's text
// in the request only; stored history is unchanged. Empty means the model
// does not see the metadata. Exposed via MessageMetadataTemplater.
MessageMetadataTemplate string
}
ProviderSpec holds the configuration needed to create a provider instance
func (*ProviderSpec) HasCredential ¶
func (s *ProviderSpec) HasCredential() bool
HasCredential returns true if the spec has a credential whose type is not "none". Factory functions use it to choose between credential-based and environment-variable-based constructors.
type ProviderTools ¶
type ProviderTools = any
ProviderTools represents provider-specific tool configuration. Each provider returns its own native format, an unexported type that callers treat as opaque. A provider may return nil when given no descriptors.
Pass the value returned by BuildTooling directly to PredictWithTools or PredictStreamWithTools.
type ProviderTransportError ¶
ProviderTransportError wraps a connection-level failure (http2 reset, TCP reset, dial timeout, etc.). IsTransient reports it as transient.
func (*ProviderTransportError) Error ¶
func (e *ProviderTransportError) Error() string
Error redacts credential-bearing query parameters. The cause is typically a *url.Error, which embeds the full request URL, and every layer that wraps this error reformats the same text, so one failure would otherwise write the credential to the log repeatedly.
Unwrap returns the raw cause, so errors.Is and errors.As work against the original *url.Error. Code that formats the unwrapped cause directly bypasses the redaction.
func (*ProviderTransportError) Unwrap ¶
func (e *ProviderTransportError) Unwrap() error
type RankedDocument ¶ added in v2.1.0
type RankedDocument struct {
// Index is the document's position in the request's Documents slice.
// This is the field callers key on: the results are reordered, so
// position in the response says nothing about which document it was.
Index int
// Score is the provider's relevance score. Higher is more relevant.
// The range is provider-specific and NOT comparable across providers
// or models — use it to order and to threshold within one provider,
// never to compare two providers' verdicts.
Score float64
// Document echoes the input text when the provider returns it. It may
// be empty even for a valid result; Index is the reliable identifier.
Document string
}
RankedDocument is one candidate's placing.
type RateLimitOptions ¶ added in v2.17.0
RateLimitOptions is a token-bucket limit on one provider instance's outbound requests: RequestsPerSecond sustained, with up to Burst sent at once. Every HTTP request the provider sends (a Predict, a PredictStream, and each retry attempt of either) takes one token, waiting for it before the request goes out. A RequestsPerSecond of zero or less is unlimited; a Burst below 1 counts as 1. The wait respects the request's context.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages available inference providers. It keeps an ID-keyed map for Get and List, and a base.Registry keyed by (name, capability) for typed lookups.
Register and Get key on provider.ID(). The typed API (Base, GetByType, GetAll) delegates to the underlying base.Registry, which keys on (provider.Name(), provider.Type()). Registry is not safe for concurrent Register, Get and Close calls.
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry creates a new provider registry.
Example ¶
ExampleNewRegistry shows creating a provider registry and listing the (initially empty) set of registered inference providers.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/providers"
)
func main() {
reg := providers.NewRegistry()
fmt.Println("providers:", len(reg.List()))
}
Output: providers: 0
func (*Registry) Base ¶
Base returns the underlying base.Registry. Useful for cross-cutting code (config loaders, metric collectors) that needs the typed API.
func (*Registry) Close ¶
Close closes the registered providers in unspecified order and stops at the first error, which it returns. The providers after the failing one stay open.
func (*Registry) Get ¶
Get retrieves an inference provider by ID. Returns the provider and a boolean indicating if it was found, matching the legacy signature.
func (*Registry) GetAll ¶
func (r *Registry) GetAll(typ base.ProviderType) []base.Provider
GetAll returns every provider of the given capability registered in the typed base.Registry.
func (*Registry) GetByType ¶
GetByType retrieves a provider by (name, capability). For non-inference types use this; for inference, the legacy single-arg Get(id) still works.
func (*Registry) Register ¶
Register adds a provider to the registry, keyed by provider.ID(), and to the typed base.Registry, keyed by provider.Name() and provider.Type().
The last registration wins in both. A provider registered under an ID that is already taken replaces the earlier one for Get, List, GetByType and GetAll alike, and the earlier provider's typed entry is removed, so the two lookups never disagree. Callers rely on this: the SDK re-registers each pooled provider as a conversation-scoped view (MediaScoped) and expects every lookup to return the view. The replaced provider is not closed.
type RequestHeaders ¶
RequestHeaders is a map of HTTP header key-value pairs
type RerankProvider ¶ added in v2.1.0
type RerankProvider interface {
// Provider supplies lifecycle and health: Name, Type, Pricing,
// Validate, Init, HealthCheck, Close.
base.Provider
// Rerank orders req.Documents by relevance to req.Query. It honors
// context cancellation and deadlines.
//
// An empty Documents slice returns an empty result and no error: having
// nothing to rank is a normal outcome of an upstream search. An empty
// Query is an error.
Rerank(ctx context.Context, req RerankRequest) (RerankResponse, error)
// MaxDocuments reports the most candidates one call accepts. Callers
// that may exceed it should batch; implementations are free to batch
// internally instead, and say so in their own docs.
MaxDocuments() int
// ID returns the configured provider identifier, e.g. "voyageai-rerank".
// This is the instance's ID from config, not the vendor name — several
// instances of one vendor can coexist.
ID() string
}
RerankProvider orders a bounded candidate list by relevance to a query.
It is not a tool and not an agent: reranking is a synchronous model-backed function with no conversation, no tool loop and no state. Hosts call it directly, typically as an optional stage after a vector search has produced more candidates than the prompt can afford to carry.
Implementations may be hosted APIs (Voyage AI, Cohere), a local cross-encoder, or an LLM-based scorer, and callers should not need to know which.
func CreateRerankProviderFromSpec ¶ added in v2.1.0
func CreateRerankProviderFromSpec(spec RerankProviderSpec) (RerankProvider, error)
CreateRerankProviderFromSpec builds a rerank provider for spec.Type. It returns an error naming the registered types when none is registered for spec.Type, which happens when the provider's package is not imported. It applies spec.Tuning after construction and returns an error when Tuning is set for a provider that is not base.HTTPTunable.
type RerankProviderFactory ¶ added in v2.1.0
type RerankProviderFactory func(spec RerankProviderSpec) (RerankProvider, error)
RerankProviderFactory builds a RerankProvider from a spec. Per-provider packages register one via init() so this package never imports them (the implementations already import it for the interface).
type RerankProviderSpec ¶ added in v2.1.0
type RerankProviderSpec struct {
// ID is a stable identifier for this instance.
ID string
// Type selects the implementation: voyageai, cohere, mock.
Type string
// Model overrides the provider's default rerank model.
Model string
// BaseURL overrides the provider's default API endpoint.
BaseURL string
// Credential carries the resolved API key. May be nil for
// providers that need no auth (e.g. the in-process mock).
Credential credentials.Credential
// AdditionalConfig carries provider-specific extras. Unknown keys are
// ignored, so a config written for one vendor does not fail on another.
AdditionalConfig map[string]any
// Platform identifies a hosting platform ("azure", "bedrock",
// "vertex"). Empty means direct API access via Credential.
Platform string
// PlatformConfig holds platform-specific settings. Only set when
// Platform != "".
PlatformConfig *PlatformConfig
// Tuning carries the provider file's headers, request_timeout and
// http_transport. CreateRerankProviderFromSpec applies it after
// construction and rejects it for a provider that is not HTTPTunable.
Tuning base.HTTPTuning
}
RerankProviderSpec is the transport-agnostic description the factory turns into a RerankProvider, mirroring EmbeddingProviderSpec. The SDK translates a pkg/config provider block into this after resolving credentials.
type RerankRequest ¶ added in v2.1.0
type RerankRequest struct {
// Query is the text documents are ranked against. Required.
Query string
// Documents are the candidates to order. The response refers back to
// them by position, so the caller keeps ownership of whatever richer
// objects these strings were rendered from.
Documents []string
// TopN caps how many results come back. Zero means "all of them",
// still ordered. A provider may return fewer than TopN but never more.
TopN int
// Model overrides the provider's default. Empty uses the default.
Model string
}
RerankRequest asks a provider to order Documents by their relevance to Query.
Unlike embedding, which scores each text on its own and leaves the comparison to the caller, a reranker reads the query and a document together. That is what makes it more accurate, and why its output cannot be cached per document the way a vector can.
type RerankResponse ¶ added in v2.1.0
type RerankResponse struct {
// Results are ordered best-first and contain at most TopN entries.
// Documents the provider dropped are simply absent.
Results []RankedDocument
// Model is the model that actually ran, which may differ from the
// requested one when the provider substitutes.
Model string
// Usage reports token consumption when the provider supplies it.
Usage *RerankUsage
}
RerankResponse holds the reordered candidates.
type RerankTransport ¶ added in v2.1.0
RerankTransport is the resolved transport for a rerank provider, mirroring EmbeddingTransport.
func ResolveRerankTransport ¶ added in v2.1.0
func ResolveRerankTransport(spec RerankProviderSpec) (RerankTransport, error)
ResolveRerankTransport turns a spec's credential into the base URL and API key a vendor constructor needs.
Platform-hosted reranking (Azure, Bedrock, Vertex) is not supported: a spec with a Platform returns an error.
type RerankUsage ¶ added in v2.1.0
type RerankUsage struct {
// TotalTokens counts query and documents together. Rerankers bill on
// the combined input; there is no output to bill for.
TotalTokens int
}
RerankUsage tracks what a rerank call cost.
type ResponseFormat ¶
type ResponseFormat struct {
// Type specifies the response format type
Type ResponseFormatType `json:"type"`
// JSONSchema is the schema to use when Type is ResponseFormatJSONSchema
// This should be a valid JSON Schema object
JSONSchema json.RawMessage `json:"json_schema,omitempty"`
// SchemaName is an optional name for the schema (used by OpenAI)
SchemaName string `json:"schema_name,omitempty"`
// Strict enables strict schema validation (OpenAI-specific)
Strict bool `json:"strict,omitempty"`
}
ResponseFormat specifies the format of the model's response
type ResponseFormatType ¶
type ResponseFormatType string
ResponseFormatType defines the type of response format
const ( // ResponseFormatText is the default text response format ResponseFormatText ResponseFormatType = "text" // ResponseFormatJSON requests JSON output from the model ResponseFormatJSON ResponseFormatType = "json_object" // ResponseFormatJSONSchema requests JSON output conforming to a schema ResponseFormatJSONSchema ResponseFormatType = "json_schema" )
type RetryBudget ¶
type RetryBudget struct {
// contains filtered or unexported fields
}
RetryBudget is a token bucket that governs how often streaming retries may actually re-dial the upstream. The initial attempt of each request is NOT gated by the budget — only retries consume tokens.
Rationale: per-call bounded retry (policy.MaxAttempts) is not enough at scale. When a single HTTP/2 connection reset kills ~100 streams at once, naive bounded retry causes 100 simultaneous reconnect attempts, which amplifies the upstream problem instead of recovering from it. The budget caps the *rate* at which retries hit the upstream so one storm cannot saturate the provider's capacity for the entire runtime.
Design: gRPC's "retry throttling" pattern, implemented with a standard golang.org/x/time/rate token bucket. Non-blocking acquire (fail-fast) — exhausted budgets return the original error immediately rather than stacking goroutines on a starved bucket.
All methods are nil-safe: a nil *RetryBudget allows every retry (equivalent to unlimited budget). This lets callers use the budget unconditionally without guarding every call site.
func NewRetryBudget ¶
func NewRetryBudget(ratePerSec float64, burst int) *RetryBudget
NewRetryBudget creates a new token bucket sized for streaming retries. ratePerSec is the sustained refill rate; burst is the maximum number of tokens that can accumulate. Returns nil when either parameter is non-positive (unlimited budget).
Typical sizing: start with rate=5/s, burst=10 and tune based on promptkit_stream_retries_total{outcome="budget_exhausted"}. These defaults are conservative: a healthy workload should almost never hit the budget, so high rejection counts are a signal that either retries are storming (upstream degraded) or the budget is undersized (bump it).
func (*RetryBudget) Available ¶
func (b *RetryBudget) Available() float64
Available returns the current number of tokens in the bucket. Intended for the promptkit_stream_retry_budget_available gauge. A nil budget returns 0; callers in the hot path also skip publishing the gauge for nil budgets (see StreamMetrics.ObserveRetryBudgetAvailable), so the return value is only observable in tests.
Note: rate.Limiter.Tokens reflects state at the time of the call; it may drift between TryAcquire and Available under concurrent load. This is fine for observability — the gauge is a trailing indicator.
func (*RetryBudget) Burst ¶
func (b *RetryBudget) Burst() int
Burst returns the configured burst size. Used by callers that want to compute saturation ratios (available / burst). Returns 0 for nil.
func (*RetryBudget) RatePerSec ¶
func (b *RetryBudget) RatePerSec() float64
RatePerSec returns the configured refill rate. Returns 0 for nil.
func (*RetryBudget) TryAcquire ¶
func (b *RetryBudget) TryAcquire() bool
TryAcquire attempts to take one token from the bucket without blocking. Returns true if a token was consumed (retry is permitted), false if the bucket is empty (retry must be rejected). A nil budget always returns true so provider code can call TryAcquire unconditionally.
type RetryableHTTPError ¶
RetryableHTTPError is returned when all retries are exhausted for a retryable HTTP status code.
func (*RetryableHTTPError) Error ¶
func (e *RetryableHTTPError) Error() string
Error implements the error interface.
type SSEFrameDetector ¶
type SSEFrameDetector struct{}
SSEFrameDetector detects server-sent event boundaries. A complete frame is one or more `data: ...` lines terminated by a blank line, optionally preceded by `:` comments or other SSE directive lines that get passed through as part of the frame bytes.
This is the framing used by OpenAI Chat Completions, OpenAI Responses API, Claude Messages, vLLM, and most SSE-based LLM providers.
func (SSEFrameDetector) PeekFirstFrame ¶
func (SSEFrameDetector) PeekFirstFrame(r io.Reader) ([]byte, error)
PeekFirstFrame reads until a `data: ...` line has been seen and then a terminating blank line. Comments and other directives before the first data line are included in the returned bytes.
If the stream closes cleanly right after the first event without a trailing blank line, this is still treated as a complete frame so downstream can decide what to do.
type SSEScanner ¶
type SSEScanner struct {
// contains filtered or unexported fields
}
SSEScanner scans Server-Sent Events (SSE) streams. Each Scan advances to the next line that starts with "data:"; other lines, including blank lines and comments, are skipped. A line longer than bufio.MaxScanTokenSize (64 KB) ends the scan with an error.
func NewSSEScanner ¶
func NewSSEScanner(r io.Reader) *SSEScanner
NewSSEScanner creates a new SSE scanner
func (*SSEScanner) Data ¶
func (s *SSEScanner) Data() string
Data returns the current event data as a string. The string is lazily allocated on first call per Scan to avoid unnecessary heap allocations when only DataBytes is needed.
func (*SSEScanner) DataBytes ¶
func (s *SSEScanner) DataBytes() []byte
DataBytes returns the current event data as a byte slice. The returned slice is only valid until the next call to Scan. Use this to avoid the string→[]byte conversion in json.Unmarshal.
func (*SSEScanner) Scan ¶
func (s *SSEScanner) Scan() bool
Scan advances to the next "data:" line and reports whether one was found.
type SendableContentProvider ¶ added in v2.17.0
type SendableContentProvider interface {
SendableMultimodalCapabilities() MultimodalCapabilities
}
SendableContentProvider is implemented by providers whose GetMultimodalCapabilities applies a config's declared capabilities list. SendableMultimodalCapabilities reports what the adapter itself can send, whatever the config declares. Request validation (ValidateMultimodalMessage) checks against it, so a partial capabilities list, often written for scenario selection, never rejects a part the adapter would send.
type StreamChunk ¶
type StreamChunk struct {
// Content is the accumulated content so far
Content string `json:"content"`
// Delta is the new content in this chunk
Delta string `json:"delta"`
// Reasoning carries reasoning/thinking tokens emitted by reasoning models
// (e.g. OpenAI o-series) before any visible content. Reasoning chunks act
// as keepalives that reset the idle timer; they carry no visible Delta and
// must not be appended to the content stream.
Reasoning string `json:"reasoning,omitempty"`
// OpaqueReasoning carries provider round-trip reasoning tokens (signatures /
// encrypted blocks) for this chunk. Never displayed, never content; preserved
// so a provider can feed it back where required (intra-turn).
OpaqueReasoning []types.OpaqueReasoning `json:"opaque_reasoning,omitempty"`
// MediaData contains raw streaming media bytes (audio, video, images).
// Data is always raw bytes, never base64. Providers decode at source.
MediaData *StreamMediaData `json:"-"`
// TokenCount is the total number of tokens so far
TokenCount int `json:"token_count"`
// DeltaTokens is the number of tokens in this delta
DeltaTokens int `json:"delta_tokens"`
// ToolCalls contains accumulated tool calls (for assistant messages that invoke tools)
ToolCalls []types.MessageToolCall `json:"tool_calls,omitempty"`
// FinishReason is nil until stream is complete
// A provider reports the normalized types.FinishReason* constants where it
// maps them (for example "stop"). Other values are "error" for a failed
// stream, "canceled" for a canceled one, "validation_failed",
// and "pending_tools"; an unmapped provider reason passes through verbatim.
FinishReason *string `json:"finish_reason,omitempty"`
// Interrupted indicates the response was interrupted (e.g., user started speaking)
// When true, clients should clear any buffered audio and prepare for a new response
Interrupted bool `json:"interrupted,omitempty"`
// Reset signals that the stream is being retried from scratch after a
// mid-stream failure. Consumers must discard all accumulated state
// (content, tool calls, cost info) and treat subsequent chunks as a
// fresh response. Only emitted when the provider's retry_window is
// set to "always" and a mid-stream error triggered a full retry.
// The retry costs tokens because the provider generates a new
// response from scratch.
Reset bool `json:"reset,omitempty"`
// Error is set if an error occurred during streaming
Error error `json:"error,omitempty"`
// Metadata contains provider-specific metadata
Metadata map[string]interface{} `json:"metadata,omitempty"`
// FinalResult contains the complete execution result (only set in the final
// chunk). For a provider stream that ends without an error it is a
// *PredictionResponse holding the content, tool calls, cost, finish reason
// and latency; see ExecutionResult.
FinalResult ExecutionResult `json:"final_result,omitempty"`
// CostInfo contains cost breakdown (only present in final chunk when FinishReason != nil)
CostInfo *types.CostInfo `json:"cost_info,omitempty"`
// PendingTools contains client-mode tools awaiting caller fulfillment.
// Only set when FinishReason is "pending_tools".
PendingTools []tools.PendingToolExecution `json:"pending_tools,omitempty"`
// Source labels the input track/speaker for fan-out routing (e.g. "caller",
// "agent"). Copied onto StreamElement.Source at the session boundary.
Source string `json:"source,omitempty"`
// contains filtered or unexported fields
}
StreamChunk represents a batch of tokens with metadata
func BargeMarker ¶ added in v2.11.0
func BargeMarker() StreamChunk
BargeMarker returns the chunk a session sends on the pump's input channel right after Barge(). When the pump reaches it, it drops the audio queued before it and keeps everything after it; the marker itself is not forwarded.
type StreamConsumer ¶
type StreamConsumer func(ctx context.Context, body io.ReadCloser, outChan chan<- StreamChunk)
StreamConsumer is called on the success path of RunStreamingRequest inside a dedicated goroutine. It receives the (possibly retry-replayed) response body and the output channel; it must fully drain the body and close outChan when done. Typical implementations wrap body in an IdleTimeoutReader + SSEScanner (or equivalent) and run the provider's existing stream parser.
type StreamEvent ¶
type StreamEvent struct {
// Type is StreamEventChunk, StreamEventComplete or StreamEventError.
Type string `json:"type"`
// Chunk is the chunk being delivered. For a complete event it is the
// stream's last chunk.
Chunk *StreamChunk `json:"chunk,omitempty"`
// Error is set for error events
Error error `json:"error,omitempty"`
// Timestamp is when the event occurred
Timestamp time.Time `json:"timestamp"`
}
StreamEvent is one observation of a provider stream, built by the stream relay in BaseProvider.RunStreamingRequest for each StreamObserver callback. An observer that also implements StreamEventObserver receives it.
type StreamEventObserver ¶ added in v2.17.0
type StreamEventObserver interface {
OnStreamEvent(event StreamEvent)
}
StreamEventObserver is implemented by a StreamObserver that also wants each observation as a StreamEvent, carrying its timestamp. OnStreamEvent is called before the matching StreamObserver callback.
type StreamInputSession ¶
type StreamInputSession interface {
// SendChunk sends a media chunk to the provider.
// Returns an error if the chunk cannot be sent or the session is closed.
// This method is safe to call from multiple goroutines.
SendChunk(ctx context.Context, chunk *types.MediaChunk) error
// SendText sends a text message to the provider during the streaming session.
// This is useful for sending text prompts or instructions during audio streaming.
// Note: This marks the turn as complete, triggering a response.
SendText(ctx context.Context, text string) error
// SendSystemContext sends a text message as context without completing the turn.
// Use this for system prompts that provide context but shouldn't trigger an immediate response.
// The audio/text that follows will be processed with this context in mind.
SendSystemContext(ctx context.Context, text string) error
// Response returns a receive-only channel for streaming responses.
// The channel is closed when the session ends or encounters an error.
// Consumers should read from this channel in a separate goroutine.
Response() <-chan StreamChunk
// Close ends the streaming session and releases resources.
// After calling Close, SendChunk and SendText will return errors.
// The Response channel will be closed.
// Close is safe to call multiple times.
Close() error
// Error returns any error that occurred during the session.
// Returns nil if no error has occurred.
Error() error
// Done returns a channel that's closed when the session ends.
// This is useful for select statements to detect session completion.
Done() <-chan struct{}
// BargeIn returns a channel that fires OUT-OF-BAND when the provider detects
// the user interrupting the agent mid-response (server-side barge-in),
// independent of the Response() FIFO.
//
// Why a separate channel: Response() carries the (possibly large) buffered
// audio of the in-flight response, and a consumer paced to real-time playback
// drains it slowly. An interruption sent in-band would queue behind that
// backlog and not be seen until playback caught up — defeating barge-in. This
// channel lets the consumer learn immediately and flush pending audio.
//
// It is buffered and best-effort: rapid repeats may coalesce (the consumer
// only needs to know the user interrupted, not how many times), and the
// producer never closes it while the session is live, so consumers should
// also select on Done(). Providers that cannot detect barge-in return a nil
// channel (never fires); embed BargeInSignal to satisfy this for free.
BargeIn() <-chan struct{}
}
StreamInputSession manages a bidirectional streaming session with a provider. The session allows sending media chunks (e.g., audio from a microphone) and receiving streaming responses from the LLM.
Example usage:
session, err := provider.CreateStreamSession(ctx, &StreamingInputConfig{
Config: types.StreamingMediaConfig{
Type: types.ContentTypeAudio,
ChunkSize: 8192,
SampleRate: 16000,
Encoding: "pcm",
Channels: 1,
},
})
if err != nil {
return err
}
defer session.Close()
// Send audio chunks in a goroutine
go func() {
for chunk := range micInput {
if err := session.SendChunk(ctx, chunk); err != nil {
log.Printf("send error: %v", err)
break
}
}
}()
// Receive responses
for chunk := range session.Response() {
if chunk.Error != nil {
log.Printf("response error: %v", chunk.Error)
break
}
fmt.Print(chunk.Delta)
}
type StreamInputSupport ¶
type StreamInputSupport interface {
Provider // Extends the base Provider interface
// CreateStreamSession creates a new bidirectional streaming session.
// The session remains active until Close() is called or an error occurs.
// Returns an error if the provider doesn't support the requested media type.
CreateStreamSession(ctx context.Context, req *StreamingInputConfig) (StreamInputSession, error)
// SupportsStreamInput returns the media types supported for streaming input.
// Common values: types.ContentTypeAudio, types.ContentTypeVideo
SupportsStreamInput() []string
// GetStreamingCapabilities returns detailed information about streaming support.
// This includes supported codecs, sample rates, and other constraints.
GetStreamingCapabilities() StreamingCapabilities
}
StreamInputSupport extends the Provider interface for bidirectional streaming. Providers that implement this interface can handle streaming media input (e.g., real-time audio) and provide streaming responses.
type StreamMediaData ¶
type StreamMediaData struct {
// Common fields
Data []byte // Raw media bytes (PCM audio, JPEG frame, H.264 chunk, etc.)
MIMEType string // e.g., "audio/pcm", "image/jpeg", "video/h264"
// Audio metadata
SampleRate int // Sample rate in Hz (e.g., 16000, 24000). 0 if not audio.
Channels int // Channel count (1=mono, 2=stereo). 0 if not audio.
// Visual metadata (image and video)
Width int // Pixels. 0 if unknown or not visual.
Height int // Pixels. 0 if unknown or not visual.
// Video/image streaming metadata
FrameRate float64 // FPS. 0 if not video.
IsKeyFrame bool // True if this is a key frame (video only).
FrameNum int64 // Sequence number for ordering frames/chunks.
}
StreamMediaData carries raw media bytes for streaming. Data is always raw bytes, never base64. Providers decode at source.
This type maps to pipeline-internal types at the StreamChunk/StreamElement boundary:
- stage.AudioData: SampleRate, Channels
- stage.ImageData: Width, Height, FrameNum
- stage.VideoData: Width, Height, FrameRate, IsKeyFrame, FrameNum
type StreamMetrics ¶
type StreamMetrics struct {
// contains filtered or unexported fields
}
StreamMetrics holds the direct-update Prometheus metrics for streaming provider calls. These are updated inline at the source (not via the event bus) so that burst-load drops on the event bus cannot corrupt autoscaling signals (see the off-bus invariant above).
All methods are nil-safe: if StreamMetrics is nil, the call is a no-op. This lets provider code unconditionally call s.StreamsInFlightInc(...) without guarding on whether metrics are configured.
func DefaultStreamMetrics ¶
func DefaultStreamMetrics() *StreamMetrics
DefaultStreamMetrics returns the process-wide StreamMetrics instance or nil if none has been registered. All StreamMetrics methods are nil-safe.
func NewStreamMetrics ¶
func NewStreamMetrics( registerer prometheus.Registerer, namespace string, constLabels prometheus.Labels, ) *StreamMetrics
NewStreamMetrics creates and registers the streaming metrics into the given registerer under the given namespace. Const labels are applied to every metric.
It returns a non-nil *StreamMetrics. Registering the same metric names into the same registry twice panics (Prometheus semantics); use RegisterDefaultStreamMetrics for a process-wide instance that registers once.
func RegisterDefaultStreamMetrics ¶
func RegisterDefaultStreamMetrics( registerer prometheus.Registerer, namespace string, constLabels prometheus.Labels, ) *StreamMetrics
RegisterDefaultStreamMetrics creates and installs a process-wide StreamMetrics instance. Safe to call multiple times with the SAME registerer — subsequent calls are no-ops. Calling with a DIFFERENT registerer is not supported and is treated as a misconfiguration (second call is ignored and the first wins).
Hosts (Arena, SDK, server) call this once during startup. Code that only cares about metrics being present calls DefaultStreamMetrics() and gets a nil on a misconfigured host, which is safe (methods no-op).
func (*StreamMetrics) ConcurrencyRejected ¶
func (m *StreamMetrics) ConcurrencyRejected(provider, reason string)
ConcurrencyRejected records one streaming request rejected by the per-provider concurrency semaphore. Reason distinguishes between caller-initiated cancellation ("context_canceled") and deadline timeout ("deadline_exceeded"); sustained spikes in either indicate the semaphore limit is undersized or upstream is saturated. Nil-safe.
func (*StreamMetrics) FrameDropAdd ¶
func (m *StreamMetrics) FrameDropAdd(direction, reason string, n int)
FrameDropAdd adds n dropped samples for (direction, reason). reason is a small closed set (e.g. "overflow"). Nil-safe.
func (*StreamMetrics) FrameDropsVec ¶
func (m *StreamMetrics) FrameDropsVec() *prometheus.CounterVec
FrameDropsVec returns the raw counter vec for cross-package tests.
func (*StreamMetrics) FrameUnderrunInc ¶
func (m *StreamMetrics) FrameUnderrunInc(direction string)
FrameUnderrunInc records one realtime-audio consumer pull that short-filled with silence (a stutter). direction is "input" or "output". Nil-safe.
func (*StreamMetrics) FrameUnderrunSamplesAdd ¶
func (m *StreamMetrics) FrameUnderrunSamplesAdd(direction string, n int)
FrameUnderrunSamplesAdd adds n silence samples substituted on underrun to the magnitude counter for direction. Nil-safe.
func (*StreamMetrics) FrameUnderrunSamplesVec ¶
func (m *StreamMetrics) FrameUnderrunSamplesVec() *prometheus.CounterVec
FrameUnderrunSamplesVec returns the raw counter vec for cross-package tests.
func (*StreamMetrics) FrameUnderrunsVec ¶
func (m *StreamMetrics) FrameUnderrunsVec() *prometheus.CounterVec
FrameUnderrunsVec returns the raw counter vec for cross-package tests.
func (*StreamMetrics) HTTPConnsInUseDec ¶
func (m *StreamMetrics) HTTPConnsInUseDec(host string)
HTTPConnsInUseDec decrements the in-use HTTP connection gauge for a host. Called by the conn-tracking transport wrapper when a request's response body is closed (or when the RoundTrip errored before returning a body). Nil-safe.
func (*StreamMetrics) HTTPConnsInUseInc ¶
func (m *StreamMetrics) HTTPConnsInUseInc(host string)
HTTPConnsInUseInc increments the in-use HTTP connection gauge for a host. Called by the conn-tracking transport wrapper at the start of each RoundTrip. Nil-safe.
func (*StreamMetrics) ObserveFirstChunkLatency ¶
func (m *StreamMetrics) ObserveFirstChunkLatency(provider string, d time.Duration)
ObserveFirstChunkLatency records the time from request dispatch to the first SSE data event being observed for a provider. Nil-safe.
func (*StreamMetrics) ObserveRetryBudgetAvailable ¶
func (m *StreamMetrics) ObserveRetryBudgetAvailable(provider, host string, budget *RetryBudget)
ObserveRetryBudgetAvailable samples the current token count of a retry budget and publishes it to the stream_retry_budget_available gauge. Intended to be called whenever a retry attempts to acquire a token — the gauge then reflects the budget state at the moment of highest interest (right before a retry decision).
A nil budget publishes nothing, so the gauge is absent when no budget is configured and reads 0 only when a budget is fully drained. Nil-safe on the receiver.
func (*StreamMetrics) ObserveStreamErrorChunksForwarded ¶
func (m *StreamMetrics) ObserveStreamErrorChunksForwarded(provider string, chunks int)
ObserveStreamErrorChunksForwarded records how many content chunks were forwarded downstream before a streaming request terminated with an error. Called exactly once per errored stream by the RunStreamingRequest relay goroutine, with the count of non-empty content chunks observed prior to the terminal error chunk. Nil-safe.
func (*StreamMetrics) PacingBehindDeadlineInc ¶
func (m *StreamMetrics) PacingBehindDeadlineInc(direction string)
PacingBehindDeadlineInc records one occurrence of the audio pacing stage being past a chunk's playback deadline (cannot hold real time). Nil-safe.
func (*StreamMetrics) PacingBehindDeadlineVec ¶
func (m *StreamMetrics) PacingBehindDeadlineVec() *prometheus.CounterVec
PacingBehindDeadlineVec returns the raw counter vec for cross-package tests.
func (*StreamMetrics) PipelineStageAudioBytesAdd ¶
func (m *StreamMetrics) PipelineStageAudioBytesAdd(stage string, bytes int)
PipelineStageAudioBytesAdd adds to the audio byte counter for a pipeline stage. Called with the raw PCM byte count of each audio element that flows through the stage. Nil-safe.
func (*StreamMetrics) PipelineStageAudioBytesVec ¶
func (m *StreamMetrics) PipelineStageAudioBytesVec() *prometheus.CounterVec
PipelineStageAudioBytesVec returns the raw counter vec for testing.
func (*StreamMetrics) PipelineStageElementInc ¶
func (m *StreamMetrics) PipelineStageElementInc(stage string)
PipelineStageElementInc increments the element counter for a pipeline stage. Called by the pipeline runner after each element flows through a stage's output channel. Nil-safe.
func (*StreamMetrics) PipelineStageElementsVec ¶
func (m *StreamMetrics) PipelineStageElementsVec() *prometheus.CounterVec
PipelineStageElementsVec returns the raw counter vec for testing.
func (*StreamMetrics) ProviderCallsInFlightDec ¶
func (m *StreamMetrics) ProviderCallsInFlightDec(provider string)
ProviderCallsInFlightDec decrements the total in-flight provider call gauge. Nil-safe.
func (*StreamMetrics) ProviderCallsInFlightInc ¶
func (m *StreamMetrics) ProviderCallsInFlightInc(provider string)
ProviderCallsInFlightInc increments the total in-flight provider call gauge. Nil-safe.
func (*StreamMetrics) ProviderRetry ¶ added in v2.7.0
func (m *StreamMetrics) ProviderRetry(provider, outcome string)
ProviderRetry records one non-streaming retry event from DoWithRetry. Outcome values: "retry", "success" (recovered after retrying) and "exhausted". Nil-safe.
func (*StreamMetrics) RetryAttempt ¶
func (m *StreamMetrics) RetryAttempt(provider, outcome string)
RetryAttempt records one streaming retry attempt with an outcome label. Outcome values: "success" (attempt that produced a usable stream), "failed" (retryable transient failure that will be retried), "exhausted" (last attempt failed, no more retries), "budget_exhausted" (retry was rejected because the per-provider retry budget had no tokens), or "retry_after_too_long" (the server's Retry-After exceeded the policy's MaxRetryAfter, so no retry was attempted), or "mid_stream_reset" (a failure after content was forwarded triggered a Reset and a fresh attempt). Nil-safe.
func (*StreamMetrics) StreamsInFlightDec ¶
func (m *StreamMetrics) StreamsInFlightDec(provider string)
StreamsInFlightDec decrements the in-flight stream gauge for a provider. Nil-safe.
func (*StreamMetrics) StreamsInFlightInc ¶
func (m *StreamMetrics) StreamsInFlightInc(provider string)
StreamsInFlightInc increments the in-flight stream gauge for a provider. Nil-safe.
type StreamObserver ¶
type StreamObserver interface {
OnChunk(chunk StreamChunk)
OnComplete(totalTokens int, duration time.Duration)
OnError(err error)
}
StreamObserver receives the events of every stream a provider opens through BaseProvider.RunStreamingRequest, for monitoring. Install one with BaseProvider.SetStreamObserver or ProviderSpec.StreamObserver; with none installed, nothing is observed.
The callbacks run on the stream's relay goroutine before the chunk reaches the caller, so they must return quickly. They run concurrently for concurrent streams. A callback that panics is recovered and the stream goes on.
- OnChunk is called for every chunk delivered without an error, including a Reset chunk and the final chunk.
- OnError is called for the error chunk that ends a stream attempt.
- OnComplete is called once when the stream ends without an error (after a Reset, the retried attempt decides), with the last TokenCount reported and the time since the stream was requested.
type StreamPump ¶
type StreamPump struct {
// BargeInSignal provides the StreamInputSession.BargeIn() channel, fired by
// Barge(). Embedded so it (and BargeIn()) are promoted to the session.
BargeInSignal
// contains filtered or unexported fields
}
StreamPump is the shared core behind every streaming provider's barge-in behavior. It decouples a session's single-threaded receive loop from the (real-time-paced) consumer of Response(), and implements the barge-in audio drop — so a new provider gets working, consistent barge-in by wiring its wire-protocol signals, not by reimplementing the concurrency.
The session owns the input channel (so it controls when no more chunks are coming, by closing it); the pump owns the output channel and an unbounded internal queue between them. Because the queue is unbounded, a slow consumer back-pressures only Response() and the queue (never the receive loop), so control events (barge-in) are handled promptly instead of waiting for the buffered audio backlog to drain.
Lifecycle: NewStreamPump(ctx, in, buf) then Start(); the receive goroutine feeds the input channel and, on exit, closes it and calls Wait() (which lets the pump drain and close Response()) before canceling ctx — so a terminal chunk is delivered before Done() fires. On a detected barge-in the session calls Barge() (fires the out-of-band BargeIn() signal and starts Dropping()), then sends BargeMarker() on its input channel, and skips still-arriving audio while Dropping() is true, clearing it at the next response boundary with ClearDrop().
The audio already queued for the interrupted response is dropped when the pump reaches the marker — in order, on the same channel as the audio. An out-of-band purge request raced the stream: the next response's first chunks could reach the pump's queue before the request did and be dropped with the interrupted audio, cutting the start of the agent's reply.
func NewStreamPump ¶
func NewStreamPump(ctx context.Context, in <-chan StreamChunk, buf int) *StreamPump
NewStreamPump creates a pump reading from in (owned and closed by the caller) and exposing a Response() channel buffered to buf. Call Start to run it.
func (*StreamPump) Barge ¶
func (p *StreamPump) Barge()
Barge handles a detected barge-in: fire the out-of-band signal so a paced consumer flushes immediately, and start skipping still-arriving audio. Non-blocking; safe from the receive goroutine. The session then sends BargeMarker() so the audio already queued for the interrupted response is dropped in order.
func (*StreamPump) ClearDrop ¶
func (p *StreamPump) ClearDrop()
ClearDrop stops skipping audio — call when a new response begins or the interrupted response completes.
func (*StreamPump) Dropping ¶
func (p *StreamPump) Dropping() bool
Dropping reports whether the interrupted response's audio should be skipped.
func (*StreamPump) Response ¶
func (p *StreamPump) Response() <-chan StreamChunk
Response returns the consumer-facing channel; the pump closes it after the input channel closes and the queue drains (or the context is canceled).
func (*StreamPump) Start ¶
func (p *StreamPump) Start()
Start launches the pump goroutine. Call exactly once.
func (*StreamPump) Wait ¶
func (p *StreamPump) Wait()
Wait blocks until the pump has finished draining and closed Response(). Call it from the receive loop's exit, after closing the input channel and before canceling the context, so any terminal chunk is delivered first.
type StreamRetryPolicy ¶
type StreamRetryPolicy struct {
// Enabled turns the retry loop on. Zero value is off.
Enabled bool
// MaxAttempts is total attempts including the initial request. Zero or a
// negative value falls back to DefaultStreamRetryMaxAttempts. A value of 1
// makes no retries. The policy has no effect unless Enabled is true.
MaxAttempts int
// InitialDelay is the base backoff before the first retry. Zero falls
// back to the default.
InitialDelay time.Duration
// MaxDelay caps per-attempt backoff. Zero falls back to the default.
MaxDelay time.Duration
// Window controls which point in the stream lifecycle is eligible for
// retry. Empty falls back to StreamRetryWindowPreFirstChunk.
Window StreamRetryWindow
// MaxRetryAfter is the longest a server's Retry-After may make a retry
// wait. A failure asking for longer is not retried at all: retrying
// sooner than the server allows only spends an attempt against a limit
// still in force. Zero falls back to DefaultStreamRetryMaxRetryAfter.
MaxRetryAfter time.Duration
}
StreamRetryPolicy governs bounded retry behavior for streaming requests. With the default window (StreamRetryWindowPreFirstChunk) it retries only failures that occur before any content chunk has been forwarded downstream.
It is separate from pipeline.RetryPolicy (which covers non-streaming requests) because the failure classes and safety constraints differ: streaming retries respect the idempotency window, use full jitter instead of half jitter to spread h2 herd resets, and default to fewer attempts.
func DisabledStreamRetryPolicy ¶
func DisabledStreamRetryPolicy() StreamRetryPolicy
DisabledStreamRetryPolicy returns a zero-value policy (retry off). Used as the BaseProvider default so callers never see nil.
func (StreamRetryPolicy) Attempts ¶
func (p StreamRetryPolicy) Attempts() int
Attempts returns the normalized number of attempts (>=1). Returns 1 when retry is disabled so callers can use it unconditionally in a for loop.
func (StreamRetryPolicy) BackoffFor ¶
func (p StreamRetryPolicy) BackoffFor(attempt int) time.Duration
BackoffFor computes the delay for the given attempt index (0-based) using full jitter: uniform random in [0, min(maxDelay, initialDelay * 2^attempt)]. It uses full jitter (as opposed to equal or decorrelated jitter) because when a single h2 connection reset kills ~100 streams, equal jitter still synchronizes the retries into narrow buckets; full jitter smears them.
func (StreamRetryPolicy) InitialDelayOrDefault ¶
func (p StreamRetryPolicy) InitialDelayOrDefault() time.Duration
InitialDelayOrDefault returns the configured initial delay or the default.
func (StreamRetryPolicy) MaxDelayOrDefault ¶
func (p StreamRetryPolicy) MaxDelayOrDefault() time.Duration
MaxDelayOrDefault returns the configured max delay or the default.
func (StreamRetryPolicy) MaxRetryAfterOrDefault ¶ added in v2.10.0
func (p StreamRetryPolicy) MaxRetryAfterOrDefault() time.Duration
MaxRetryAfterOrDefault returns the configured Retry-After cap or the default.
func (StreamRetryPolicy) RetryDelay ¶ added in v2.10.0
func (p StreamRetryPolicy) RetryDelay(attempt int, retryAfter time.Duration) (delay time.Duration, ok bool)
RetryDelay returns how long to wait before retrying after the given attempt (0-based) failed, honoring the server's Retry-After when it sent one: the wait is the longer of Retry-After and the jittered backoff, so a rate limit is not retried while still in force. ok is false when Retry-After exceeds MaxRetryAfter, and the caller should stop retrying rather than retry early.
type StreamRetryRequest ¶
type StreamRetryRequest struct {
Policy StreamRetryPolicy
Budget *RetryBudget // nil means unbounded retries
ProviderName string
Host string // metric label; may be empty
IdleTimeout time.Duration
RequestFn func(ctx context.Context) (*http.Request, error)
Client *http.Client
// FrameDetector identifies the first complete protocol frame on
// the response body so the retry driver knows when the stream is
// established and retry must not fire. Nil defaults to
// SSEFrameDetector. Use NDJSONFrameDetector for newline-delimited JSON,
// JSONArrayFrameDetector for Gemini, or a custom FrameDetector
// for other protocols.
FrameDetector FrameDetector
}
StreamRetryRequest bundles the dependencies for a streaming retry attempt: the policy, budget, metric labels, request factory and HTTP client.
type StreamRetryResult ¶
type StreamRetryResult struct {
// Response is the HTTP response of the successful attempt. Body has
// already been wrapped; callers must not read directly from
// Response.Body. Use Body instead.
Response *http.Response
// Body is a composite reader that first replays the SSE event bytes
// consumed by the peek, then streams the remainder of the response.
// Closing this closes the underlying Response.Body.
Body io.ReadCloser
// Attempts is the total number of attempts made (1 on first-try success).
Attempts int
}
StreamRetryResult holds the successfully opened streaming response after the pre-first-chunk retry loop. The caller takes ownership of Body (which is a composite reader re-prepending the peeked first SSE event), and must close it.
func OpenStreamWithRetry ¶
func OpenStreamWithRetry( ctx context.Context, policy StreamRetryPolicy, providerName string, idleTimeout time.Duration, requestFn func(ctx context.Context) (*http.Request, error), client *http.Client, ) (*StreamRetryResult, error)
OpenStreamWithRetry executes requestFn and peeks the first SSE data event on the response body. If Do() returns a retryable error, or the response status is retryable, or the body fails to produce a first SSE event within the idle window, the attempt is discarded and retried up to the policy's MaxAttempts. On success, the buffered bytes are replayed into the returned Body so downstream SSE parsers see a contiguous stream.
This function only retries in the pre-first-chunk window — that is, only while no content bytes have been surfaced to the caller. It never reads past the end of the first SSE event payload.
When policy.Enabled is false this is equivalent to a single Do() + peek: on success the body is still wrapped to replay the peeked bytes, but no retry is performed.
Thin wrapper over OpenStreamWithRetryRequest for callers that don't need the budget or host-label parameters.
func OpenStreamWithRetryRequest ¶
func OpenStreamWithRetryRequest(ctx context.Context, req *StreamRetryRequest) (*StreamRetryResult, error)
OpenStreamWithRetryRequest is the full form of OpenStreamWithRetry that accepts a budget and host label. Retries beyond the initial attempt must acquire a token from req.Budget (if non-nil) before re-dialing; an empty budget causes the function to return the last error immediately rather than waiting for token refill. It returns an error when req is nil.
type StreamRetryWindow ¶
type StreamRetryWindow string
StreamRetryWindow enumerates the points at which a streaming request may still be retried.
const ( // StreamRetryWindowPreFirstChunk retries only while no content chunk // has been forwarded downstream. This is the safe default that avoids // any content duplication. StreamRetryWindowPreFirstChunk StreamRetryWindow = "pre_first_chunk" // StreamRetryWindowAlways retries on any stream failure, including // after content has been forwarded. On mid-stream failure the relay // emits a StreamChunk with Reset=true so consumers discard // accumulated state, then retries the full request from scratch. // The retry produces a new response (LLMs are non-deterministic) // and costs additional tokens. Off by default. StreamRetryWindowAlways StreamRetryWindow = "always" )
type StreamScanner ¶
StreamScanner is the interface for scanning streaming responses. Both SSE (Server-Sent Events) and binary event-stream formats implement this.
type StreamSemaphore ¶
type StreamSemaphore struct {
// contains filtered or unexported fields
}
StreamSemaphore caps the number of concurrent streaming requests a provider will have in flight at any one time. Acquire blocks (subject to context cancellation) when the limit is reached, so the caller's deadline controls fail-fast vs. queueing behavior: a short context means "reject me quickly if you're full", a long one means "queue".
Rationale: per-request bounded retry + budget does not bound the *number* of streams a provider can hold open. At 1000 concurrent streams each provider holds ~1000 goroutines, timers, and channel buffers, even though it only needs a handful of h2 connections to serve them. The semaphore turns unbounded goroutine growth into back-pressure that surfaces cleanly at the caller.
Design: wraps golang.org/x/sync/semaphore.Weighted. Nil-safe — a nil *StreamSemaphore never blocks and has a no-op Release, so callers can use it unconditionally.
func NewStreamSemaphore ¶
func NewStreamSemaphore(limit int) *StreamSemaphore
NewStreamSemaphore returns a semaphore with the given concurrent-stream limit. Returns nil when limit is zero or negative, which callers interpret as "unlimited" (no gating).
func (*StreamSemaphore) Acquire ¶
func (s *StreamSemaphore) Acquire(ctx context.Context) error
Acquire blocks until the semaphore has capacity or the context is done. Returns nil on successful acquire, or the context error on cancellation/deadline. A nil semaphore always returns nil immediately (unlimited).
Callers MUST call Release exactly once for every successful Acquire, and MUST NOT call Release after an Acquire that returned an error.
func (*StreamSemaphore) Limit ¶
func (s *StreamSemaphore) Limit() int
Limit returns the configured concurrent-stream limit. Returns 0 for a nil receiver (interpreted as "unlimited" by observability consumers).
func (*StreamSemaphore) Release ¶
func (s *StreamSemaphore) Release()
Release returns one slot to the semaphore. Nil-safe.
Release of a token that was not acquired will cause semaphore.Weighted to panic — callers must pair each successful Acquire with exactly one Release, typically via defer.
type StreamingCapabilities ¶
type StreamingCapabilities struct {
// SupportedMediaTypes lists the media types that can be streamed
// Values: types.ContentTypeAudio, types.ContentTypeVideo
SupportedMediaTypes []string `json:"supported_media_types"`
// Audio capabilities
Audio *AudioStreamingCapabilities `json:"audio,omitempty"`
// Video capabilities
Video *VideoStreamingCapabilities `json:"video,omitempty"`
// BidirectionalSupport indicates if the provider supports full bidirectional streaming
BidirectionalSupport bool `json:"bidirectional_support"`
// MaxSessionDuration is the maximum duration for a streaming session (in seconds)
// Zero means no limit
MaxSessionDuration int `json:"max_session_duration,omitempty"`
// MinChunkSize is the minimum chunk size in bytes
MinChunkSize int `json:"min_chunk_size,omitempty"`
// MaxChunkSize is the maximum chunk size in bytes
MaxChunkSize int `json:"max_chunk_size,omitempty"`
}
StreamingCapabilities describes what streaming features a provider supports.
type StreamingInputConfig ¶
type StreamingInputConfig struct {
// Config specifies the media streaming configuration (codec, sample rate, etc.)
Config types.StreamingMediaConfig `json:"config"`
// SystemInstruction is the system prompt to configure the model's behavior.
// For Gemini Live API, this is included in the setup message.
SystemInstruction string `json:"system_instruction,omitempty"`
// Tools defines functions the model can call during the session.
// When configured, the model returns structured tool calls instead of
// speaking them as text. Supported by Gemini Live API.
Tools []StreamingToolDefinition `json:"tools,omitempty"`
// Metadata contains provider-specific session configuration
// Example: {"response_modalities": ["TEXT", "AUDIO"]} for Gemini
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Sampling carries the opened prompt's sampling parameters into the
// session. A provider sends those its realtime API takes and reports the
// rest with WarnUnsentParams. Nil sends none.
Sampling *StreamingSampling `json:"sampling,omitempty"`
}
StreamingInputConfig configures a new streaming input session.
func (*StreamingInputConfig) Validate ¶
func (r *StreamingInputConfig) Validate() error
Validate checks that the streaming media Config is valid.
type StreamingSampling ¶ added in v2.13.0
type StreamingSampling struct {
MaxTokens int `json:"max_tokens,omitempty"`
Temperature float32 `json:"temperature,omitempty"`
TemperatureSet bool `json:"temperature_set,omitempty"`
TopP float32 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
FrequencyPenalty *float32 `json:"frequency_penalty,omitempty"`
PresencePenalty *float32 `json:"presence_penalty,omitempty"`
}
StreamingSampling is a prompt's sampling parameters for a realtime session, with PredictionRequest's meaning: zero MaxTokens and TopP, and nil pointers, are unset, and Temperature counts only with TemperatureSet or when non-zero.
func (*StreamingSampling) Request ¶ added in v2.13.0
func (s *StreamingSampling) Request() *PredictionRequest
Request returns s as a PredictionRequest's sampling fields, for WarnUnsentParams. A nil s returns an empty request.
type StreamingToolDefinition ¶
type StreamingToolDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]interface{} `json:"parameters,omitempty"` // JSON Schema
}
StreamingToolDefinition represents a function/tool available in streaming sessions.
type ToolDescriptor ¶
type ToolDescriptor struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"input_schema"`
OutputSchema json.RawMessage `json:"output_schema"`
}
ToolDescriptor represents a tool that can be used by providers
type ToolResponse ¶
type ToolResponse struct {
ToolCallID string `json:"tool_call_id"`
Result string `json:"result"`
IsError bool `json:"is_error,omitempty"` // True if the tool execution failed
}
ToolResponse represents a single tool execution result.
type ToolResponseSupport ¶
type ToolResponseSupport interface {
// SendToolResponse sends the result of a tool execution back to the model.
// The toolCallID must match the ID from the MessageToolCall.
// The result is typically JSON-encoded but the format depends on the tool.
// After receiving the tool response, the model will continue generating.
SendToolResponse(ctx context.Context, toolCallID string, result string) error
// SendToolResponses sends multiple tool results at once (for parallel tool calls).
// This is more efficient than sending individual responses for providers that
// support batched tool responses.
SendToolResponses(ctx context.Context, responses []ToolResponse) error
}
ToolResponseSupport is an optional interface for streaming sessions that support tool calling. When the model returns a tool call, the caller can execute the tool and send the result back using this interface. The session will then continue generating a response based on the tool result.
Use type assertion to check if a StreamInputSession supports this interface:
if toolSession, ok := session.(ToolResponseSupport); ok {
err := toolSession.SendToolResponse(ctx, toolCallID, result)
}
type ToolResult ¶
type ToolResult = types.MessageToolResult
ToolResult represents the result of a tool execution This is an alias to types.MessageToolResult for provider-specific context
type ToolSupport ¶
type ToolSupport interface {
Provider // Extends the base Provider interface
// BuildTooling converts tool descriptors to provider-native format.
// Returns a provider-specific type that should be passed to PredictWithTools.
BuildTooling(descriptors []*ToolDescriptor) (ProviderTools, error)
// PredictWithTools performs a predict request with tool support.
// The tools parameter should be the value returned by BuildTooling.
PredictWithTools(
ctx context.Context,
req PredictionRequest,
tools ProviderTools,
toolChoice string,
) (PredictionResponse, []types.MessageToolCall, error)
// PredictStreamWithTools performs a streaming predict request with tool support.
// The tools parameter should be the value returned by BuildTooling.
PredictStreamWithTools(
ctx context.Context,
req PredictionRequest,
tools ProviderTools,
toolChoice string,
) (<-chan StreamChunk, error)
}
ToolSupport interface for providers that support tool/function calling
type UnsupportedContentError ¶
type UnsupportedContentError struct {
Provider string // Provider ID
ContentType string // "image", "audio", "video", "document", or "multimodal"
Message string // Human-readable error message
PartIndex int // Index of the unsupported content part; -1 when the error is not about one part
MIMEType string // Specific MIME type that's unsupported (if applicable)
}
UnsupportedContentError is returned when a provider doesn't support certain content types
func (*UnsupportedContentError) Error ¶
func (e *UnsupportedContentError) Error() string
Error returns the message, naming the part when PartIndex is not negative.
type UnsupportedProviderError ¶
type UnsupportedProviderError struct {
ProviderType string
}
UnsupportedProviderError is returned when no factory is registered for a provider type. When the type names a hosting platform (bedrock, vertex or azure), the message says which vendor types to use instead.
func (*UnsupportedProviderError) Error ¶
func (e *UnsupportedProviderError) Error() string
Error returns the error message for this unsupported provider error.
type UnsupportedProviderPlatformError ¶
UnsupportedProviderPlatformError is returned when a provider type is recognized but the requested platform does not host that vendor's models (for example openai on vertex). It is returned at provider construction, so the failure surfaces at configuration time rather than on the first request.
func (*UnsupportedProviderPlatformError) Error ¶
func (e *UnsupportedProviderPlatformError) Error() string
Error returns the error message for this unsupported pair.
type ValidationAbortError ¶
type ValidationAbortError struct {
Reason string
Chunk StreamChunk
}
ValidationAbortError is returned when a streaming validator aborts a stream
func (*ValidationAbortError) Error ¶
func (e *ValidationAbortError) Error() string
Error returns the error message for this validation abort error.
type VideoResolution ¶
VideoResolution represents a video resolution.
func (VideoResolution) String ¶
func (r VideoResolution) String() string
String returns a string representation of the resolution (e.g., "1920x1080")
type VideoStreamingCapabilities ¶
type VideoStreamingCapabilities struct {
// SupportedEncodings lists supported video encodings
// Common values: "h264", "vp8", "vp9", "av1"
SupportedEncodings []string `json:"supported_encodings"`
// SupportedResolutions lists supported resolutions (width x height)
SupportedResolutions []VideoResolution `json:"supported_resolutions"`
// SupportedFrameRates lists supported frame rates
// Common values: 15, 24, 30, 60
SupportedFrameRates []int `json:"supported_frame_rates"`
// PreferredEncoding is the recommended encoding
PreferredEncoding string `json:"preferred_encoding"`
// PreferredResolution is the recommended resolution
PreferredResolution VideoResolution `json:"preferred_resolution"`
// PreferredFrameRate is the recommended frame rate
PreferredFrameRate int `json:"preferred_frame_rate"`
}
VideoStreamingCapabilities describes video streaming support.
Source Files
¶
- base_embedding.go
- base_provider.go
- base_rerank.go
- bedrock_eventstream.go
- embedding.go
- embedding_factory.go
- embedding_platform.go
- embedding_transport.go
- errors.go
- extra_body.go
- finish_reason.go
- frame_detector.go
- http_transport_tracking.go
- idle_timeout.go
- jitter_health.go
- media_loader.go
- multimodal.go
- provider.go
- provider_contract_integration.go
- redact_url.go
- registry.go
- rejected_params.go
- rerank.go
- rerank_factory.go
- rerank_mock.go
- retry.go
- sse.go
- stream_metrics.go
- stream_pump.go
- stream_retry.go
- stream_retry_budget.go
- stream_retry_driver.go
- stream_semaphore.go
- stream_tap.go
- streaming.go
- streaming_input.go
- utils.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package all provides a convenient way to register all PromptKit providers with a single import.
|
Package all provides a convenient way to register all PromptKit providers with a single import. |
|
Package base defines the unified provider abstraction shared across all PromptKit provider types (inference, TTS, STT, embedding, image generation).
|
Package base defines the unified provider abstraction shared across all PromptKit provider types (inference, TTS, STT, embedding, image generation). |
|
Package bedrock provides embedding generation via AWS Bedrock's platform-native models.
|
Package bedrock provides embedding generation via AWS Bedrock's platform-native models. |
|
Package claude provides Anthropic Claude LLM provider integration.
|
Package claude provides Anthropic Claude LLM provider integration. |
|
Package cohere provides reranking via the Cohere Rerank API.
|
Package cohere provides reranking via the Cohere Rerank API. |
|
Package conformance contains integration tests that verify each inference provider implementation satisfies the base.Provider interface.
|
Package conformance contains integration tests that verify each inference provider implementation satisfies the base.Provider interface. |
|
Package gemini provides Gemini Live API streaming support.
|
Package gemini provides Gemini Live API streaming support. |
|
Package huggingface implements providers.EmbeddingProvider against Hugging Face's feature-extraction API: the serverless Inference Providers router (https://router.huggingface.co/hf-inference) and dedicated Inference Endpoints, which serve the same request and response shape.
|
Package huggingface implements providers.EmbeddingProvider against Hugging Face's feature-extraction API: the serverless Inference Providers router (https://router.huggingface.co/hf-inference) and dedicated Inference Endpoints, which serve the same request and response shape. |
|
Package imagen provides Google Imagen image generation provider integration.
|
Package imagen provides Google Imagen image generation provider integration. |
|
internal
|
|
|
streaming
Package streaming provides a common WebSocket streaming session abstraction used by provider implementations (OpenAI Realtime, Gemini Live, etc.).
|
Package streaming provides a common WebSocket streaming session abstraction used by provider implementations (OpenAI Realtime, Gemini Live, etc.). |
|
Package mock provides mock provider implementation for testing and development.
|
Package mock provides mock provider implementation for testing and development. |
|
Package ollama provides Ollama LLM provider integration for local development.
|
Package ollama provides Ollama LLM provider integration for local development. |
|
Package openai provides OpenAI LLM provider integration.
|
Package openai provides OpenAI LLM provider integration. |
|
Package replay provides a provider that replays recorded sessions deterministically.
|
Package replay provides a provider that replays recorded sessions deterministically. |
|
Package schemaadapt walks a JSON Schema so provider adapters can rewrite it into the dialect their API accepts.
|
Package schemaadapt walks a JSON Schema so provider adapters can rewrite it into the dialect their API accepts. |
|
Package vertex provides embedding generation via Google Vertex AI's text-embedding models.
|
Package vertex provides embedding generation via Google Vertex AI's text-embedding models. |
|
Package vllm provides vLLM LLM provider integration for high-performance inference.
|
Package vllm provides vLLM LLM provider integration for high-performance inference. |
|
Package voyageai provides embedding generation via the Voyage AI API.
|
Package voyageai provides embedding generation via the Voyage AI API. |