Documentation
¶
Index ¶
- func DoWithResultTyped[T any](r Retryer, ctx context.Context, fn func() (T, error)) (T, error)
- func IsRetryableError(err error) bool
- func WrapRetryable(err error) error
- type Alert
- type AlertHandler
- type AlertType
- type BlockingRateLimiter
- type BudgetConfig
- type BudgetStatus
- type Manager
- type ManagerConfig
- type RetryPolicy
- type RetryableError
- type Retryer
- type TokenBudgetManager
- func (m *TokenBudgetManager) CheckBudget(ctx context.Context, estimatedTokens int, estimatedCost float64) error
- func (m *TokenBudgetManager) GetStatus() BudgetStatus
- func (m *TokenBudgetManager) OnAlert(handler AlertHandler)
- func (m *TokenBudgetManager) RecordUsage(record UsageRecord)
- func (m *TokenBudgetManager) Reset()
- func (m *TokenBudgetManager) WaitAlerts(ctx context.Context) error
- type UsageRecord
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DoWithResultTyped ¶
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 ¶
IsRetryableError 检查错误是否被 WrapRetryable 包装为可重试错误。 注意:这与 types.IsRetryable 语义不同 —— 本函数检查 *RetryableError 包装类型, 而 types.IsRetryable 检查 *types.Error 的 Retryable 字段。
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 BlockingRateLimiter ¶
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 配置符号预算管理 。
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 (*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 记录请求后预算消耗。
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) 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"`
}
用法记录代表单一使用记录.