policy

package
v1.4.6 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DoWithResultTyped

func DoWithResultTyped[T any](r Retryer, ctx context.Context, fn func() (T, error)) (T, error)

DoWithResultTyped is a type-safe generic wrapper around Retryer.DoWithResult. It eliminates the need for type assertions on the return value.

Usage:

val, err := retry.DoWithResultTyped[int](r, ctx, func() (int, error) {
    return 42, nil
})

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError 检查错误是否被 WrapRetryable 包装为可重试错误。 注意:这与 types.IsRetryable 语义不同 —— 本函数检查 *RetryableError 包装类型, 而 types.IsRetryable 检查 *types.Error 的 Retryable 字段。

func WrapRetryable

func WrapRetryable(err error) error

WrapRetryable 将错误包装为可重试错误

Types

type Alert

type Alert struct {
	Type      AlertType `json:"type"`
	Message   string    `json:"message"`
	Threshold float64   `json:"threshold"`
	Current   float64   `json:"current"`
	Timestamp time.Time `json:"timestamp"`
}

警报代表预算警报。

type AlertHandler

type AlertHandler func(alert Alert)

警报汉德勒处理预算警报.

type AlertType

type AlertType string

提醒Type代表预算提醒的类型.

const (
	AlertTokenMinute AlertType = "token_minute_threshold"
	AlertTokenHour   AlertType = "token_hour_threshold"
	AlertTokenDay    AlertType = "token_day_threshold"
	AlertCostDay     AlertType = "cost_day_threshold"
	AlertLimitHit    AlertType = "limit_hit"
)

type BlockingRateLimiter

type BlockingRateLimiter interface {
	Wait(ctx context.Context) error
}

BlockingRateLimiter 定义阻塞式限流接口。

type BudgetConfig

type BudgetConfig struct {
	MaxTokensPerRequest int           `json:"max_tokens_per_request"`
	MaxTokensPerMinute  int           `json:"max_tokens_per_minute"`
	MaxTokensPerHour    int           `json:"max_tokens_per_hour"`
	MaxTokensPerDay     int           `json:"max_tokens_per_day"`
	MaxCostPerRequest   float64       `json:"max_cost_per_request"`
	MaxCostPerDay       float64       `json:"max_cost_per_day"`
	AlertThreshold      float64       `json:"alert_threshold"` // 0.0-1.0, alert when usage exceeds this
	AutoThrottle        bool          `json:"auto_throttle"`
	ThrottleDelay       time.Duration `json:"throttle_delay"`
}

预算Config 配置符号预算管理 。

func DefaultBudgetConfig

func DefaultBudgetConfig() BudgetConfig

默认预览返回合理的默认值 。

type BudgetStatus

type BudgetStatus struct {
	TokensUsedMinute  int64      `json:"tokens_used_minute"`
	TokensUsedHour    int64      `json:"tokens_used_hour"`
	TokensUsedDay     int64      `json:"tokens_used_day"`
	CostUsedDay       float64    `json:"cost_used_day"`
	MinuteUtilization float64    `json:"minute_utilization"`
	HourUtilization   float64    `json:"hour_utilization"`
	DayUtilization    float64    `json:"day_utilization"`
	CostUtilization   float64    `json:"cost_utilization"`
	IsThrottled       bool       `json:"is_throttled"`
	ThrottleUntil     *time.Time `json:"throttle_until,omitempty"`
}

预算状况是目前的预算状况。

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager 聚合预算、限流和重试策略。

func NewManager

func NewManager(cfg ManagerConfig) *Manager

NewManager 创建策略管理器。

func (*Manager) Budget

func (m *Manager) Budget() *TokenBudgetManager

Budget 返回预算管理器引用。

func (*Manager) PreCheck

func (m *Manager) PreCheck(ctx context.Context, estimatedTokens int, estimatedCostUSD float64) error

PreCheck 执行请求前策略检查。

func (*Manager) RecordUsage

func (m *Manager) RecordUsage(record UsageRecord)

RecordUsage 记录请求后预算消耗。

func (*Manager) Retry

func (m *Manager) Retry() *RetryPolicy

Retry 返回统一重试策略。

type ManagerConfig

type ManagerConfig struct {
	Budget      *TokenBudgetManager
	RetryPolicy *RetryPolicy
	RateLimiter BlockingRateLimiter
}

ManagerConfig 定义策略管理器依赖。

type RetryPolicy

type RetryPolicy struct {
	MaxRetries      int                                               // 最大重试次数(0 表示不重试)
	InitialBackoff  time.Duration                                     // 初始退避时间
	MaxBackoff      time.Duration                                     // 最大退避时间
	Multiplier      float64                                           // 延迟时间倍增因子(指数退避)
	Jitter          bool                                              // 是否添加随机抖动(防止雪崩)
	RetryableErrors []error                                           // 可重试的错误类型(为空则重试所有错误)
	OnRetry         func(attempt int, err error, delay time.Duration) // 重试回调
}

RetryPolicy 定义重试策略配置 遵循 KISS 原则:简单但功能完整的重试策略

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy 返回默认的重试策略 适用于大部分 LLM API 调用场景

type RetryableError

type RetryableError struct {
	Err error
}

RetryableError 可重试的错误类型 用于标记哪些错误应该触发重试

func (*RetryableError) Error

func (e *RetryableError) Error() string

func (*RetryableError) Unwrap

func (e *RetryableError) Unwrap() error

type Retryer

type Retryer interface {
	// Do 执行函数,失败时根据策略重试
	Do(ctx context.Context, fn func() error) error

	// DoWithResult 执行函数并返回结果,失败时根据策略重试
	DoWithResult(ctx context.Context, fn func() (any, error)) (any, error)
}

Retryer 重试器接口 提供统一的重试能力

func NewBackoffRetryer

func NewBackoffRetryer(policy *RetryPolicy, logger *zap.Logger) Retryer

NewBackoffRetryer 创建指数退避重试器

type TokenBudgetManager

type TokenBudgetManager struct {
	// contains filtered or unexported fields
}

TokenBudgetManager管理符名预算并强制执行限制.

func NewTokenBudgetManager

func NewTokenBudgetManager(config BudgetConfig, logger *zap.Logger) *TokenBudgetManager

NewTokenBudgetManager 创建了新的代币预算管理器.

func (*TokenBudgetManager) CheckBudget

func (m *TokenBudgetManager) CheckBudget(ctx context.Context, estimatedTokens int, estimatedCost float64) error

检查预算是否在预算范围内 。 所有计数器访问统一在 mu 锁保护下进行,避免 mutex/atomic 混用导致的不一致。

func (*TokenBudgetManager) GetStatus

func (m *TokenBudgetManager) GetStatus() BudgetStatus

Get Status 返回当前预算状况 。

func (*TokenBudgetManager) OnAlert

func (m *TokenBudgetManager) OnAlert(handler AlertHandler)

OnAlert登记了一个警报处理器。

func (*TokenBudgetManager) RecordUsage

func (m *TokenBudgetManager) RecordUsage(record UsageRecord)

记录Usage记录符和成本使用. 所有计数器更新统一在 mu 锁保护下进行。

func (*TokenBudgetManager) Reset

func (m *TokenBudgetManager) Reset()

重置所有计数器(用于测试).

func (*TokenBudgetManager) WaitAlerts

func (m *TokenBudgetManager) WaitAlerts(ctx context.Context) error

WaitAlerts waits for all in-flight alert handlers to complete or context cancellation.

type UsageRecord

type UsageRecord struct {
	Timestamp time.Time `json:"timestamp"`
	Tokens    int       `json:"tokens"`
	Cost      float64   `json:"cost"`
	Model     string    `json:"model"`
	RequestID string    `json:"request_id"`
	UserID    string    `json:"user_id,omitempty"`
	AgentID   string    `json:"agent_id,omitempty"`
}

用法记录代表单一使用记录.

Jump to

Keyboard shortcuts

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