Documentation
¶
Overview ¶
Package middleware provides composable policies for model calls.
Index ¶
- Variables
- func ApproximateTokenCount(text string) int64
- func ContextWithTokenBudget(ctx context.Context, budget *TokenBudget) context.Context
- func Wrap(base models.Agent, policies ...Middleware) (models.Agent, error)
- type Middleware
- type MiddlewareFunc
- type RateLimitMode
- type RateLimitPolicy
- type RetryPolicy
- type TimeoutPolicy
- type TokenBudget
- type TokenBudgetError
- type TokenBudgetPolicy
- type TokenEstimator
Constants ¶
This section is empty.
Variables ¶
var ErrRateLimitExceeded = errors.New("model rate limit exceeded")
ErrRateLimitExceeded indicates that a reject-mode limiter had no permit.
var ErrTokenBudgetExceeded = errors.New("model token budget exceeded")
ErrTokenBudgetExceeded indicates that a model call would exceed, or has already generated output beyond, its configured estimated token budget.
Functions ¶
func ApproximateTokenCount ¶
ApproximateTokenCount estimates one token per four UTF-8 bytes. It is a portable fallback, not provider billing data.
func ContextWithTokenBudget ¶
func ContextWithTokenBudget(ctx context.Context, budget *TokenBudget) context.Context
ContextWithTokenBudget associates a per-run budget with ctx. It overrides the fallback budget configured on TokenBudgetPolicy.
Types ¶
type Middleware ¶
Middleware wraps a model with one policy. Implementations should preserve models.ToolCallingAgent when possible and return models.ErrToolCallingUnsupported when the wrapped model does not support native tool calls.
type MiddlewareFunc ¶
MiddlewareFunc adapts a function into Middleware.
type RateLimitMode ¶
type RateLimitMode uint8
RateLimitMode controls what happens when no request permit is immediately available.
const ( // RateLimitWait waits for the next permit and respects context cancellation. RateLimitWait RateLimitMode = iota // RateLimitReject fails immediately with ErrRateLimitExceeded. RateLimitReject )
type RateLimitPolicy ¶
type RateLimitPolicy struct {
Requests int
Per time.Duration
Burst int
Mode RateLimitMode
}
RateLimitPolicy limits model request starts. One permit is consumed for each retry attempt when this policy is placed inside RetryPolicy.
type RetryPolicy ¶
type RetryPolicy struct {
MaxAttempts int
InitialBackoff time.Duration
MaxBackoff time.Duration
Multiplier float64
Jitter float64
DisableJitter bool
// ShouldRetry overrides the default decision. The default retries all
// non-cancellation errors except policy rejections and unsupported native
// tool calling. A deadline created by an inner timeout policy is retryable
// while expiry of the caller's context is not.
ShouldRetry func(context.Context, error) bool
}
RetryPolicy retries model calls that fail before producing a result. Stream creation can be retried, but errors emitted after a stream starts cannot be retried safely because doing so could duplicate chunks.
type TimeoutPolicy ¶
TimeoutPolicy bounds a complete model operation. For streams, the deadline remains active until the stream finishes rather than only covering setup. The wrapper can return on time even if a custom provider ignores context, though such a provider may continue its work in the background.
type TokenBudget ¶
type TokenBudget struct {
// contains filtered or unexported fields
}
TokenBudget is a concurrency-safe, reusable estimated-token allowance. Input charges are rejected before a model call. Output charges are recorded after generation, so Used may exceed Max when a non-streaming provider returns more output than remained.
func NewTokenBudget ¶
func NewTokenBudget(max int64, estimator TokenEstimator) (*TokenBudget, error)
NewTokenBudget creates a token budget. A nil estimator uses ApproximateTokenCount.
func TokenBudgetFromContext ¶
func TokenBudgetFromContext(ctx context.Context) (*TokenBudget, bool)
TokenBudgetFromContext returns the budget associated with ctx.
func (*TokenBudget) Remaining ¶
func (b *TokenBudget) Remaining() int64
Remaining returns the estimated tokens still available, clamped to zero.
func (*TokenBudget) Reset ¶
func (b *TokenBudget) Reset()
Reset clears all charges. It is safe to call concurrently, though callers should normally reset only when no requests using the budget are active.
func (*TokenBudget) Used ¶
func (b *TokenBudget) Used() int64
Used returns the estimated tokens charged so far.
type TokenBudgetError ¶
TokenBudgetError describes a rejected budget charge.
func (*TokenBudgetError) Error ¶
func (e *TokenBudgetError) Error() string
func (*TokenBudgetError) Unwrap ¶
func (e *TokenBudgetError) Unwrap() error
Unwrap supports errors.Is(err, ErrTokenBudgetExceeded).
type TokenBudgetPolicy ¶
type TokenBudgetPolicy struct {
Budget *TokenBudget
}
TokenBudgetPolicy enforces the context budget when present, otherwise Budget. A nil fallback is valid and makes the policy context-only.
type TokenEstimator ¶
TokenEstimator estimates the number of tokens in text. Provider tokenizers can be supplied when exact accounting is required.