feat(generation): enforce prompt budget with whole article eviction (#47)
This commit is contained in:
67
backend/internal/ai/provider_failure.go
Normal file
67
backend/internal/ai/provider_failure.go
Normal file
@ -0,0 +1,67 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Never inspect human-readable messages or retain an original error chain.
|
||||
func safeProviderFailure(ctx context.Context, err error) error {
|
||||
var timeout interface{ Timeout() bool }
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) {
|
||||
return generation.ProviderFailure("summary_timeout")
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled) {
|
||||
return generation.ProviderFailure("summary_canceled")
|
||||
}
|
||||
status, code := 0, ""
|
||||
var local *summaryHTTPError
|
||||
var api *openai.APIError
|
||||
var request *openai.RequestError
|
||||
switch {
|
||||
case errors.As(err, &local):
|
||||
status, code = local.status, local.code
|
||||
case errors.As(err, &api):
|
||||
status = api.HTTPStatusCode
|
||||
code, _ = api.Code.(string)
|
||||
if code == "" {
|
||||
code = api.Type
|
||||
}
|
||||
case errors.As(err, &request):
|
||||
status = request.HTTPStatusCode
|
||||
}
|
||||
category := "summary_failed"
|
||||
switch status {
|
||||
case 401, 403:
|
||||
category = "summary_auth_failed"
|
||||
case 404, 410:
|
||||
category = "summary_model_rejected"
|
||||
case 413:
|
||||
category = "summary_provider_limit"
|
||||
case 429:
|
||||
category = "summary_rate_limited"
|
||||
case 408, 504:
|
||||
category = "summary_timeout"
|
||||
default:
|
||||
if status >= 500 && status <= 599 {
|
||||
category = "summary_unavailable"
|
||||
} else {
|
||||
switch strings.ToLower(code) {
|
||||
case "invalid_api_key", "authentication_error", "permission_denied", "unauthenticated", "api_key_invalid", "api_key_expired":
|
||||
category = "summary_auth_failed"
|
||||
case "model_not_found", "not_found_error", "not_found":
|
||||
category = "summary_model_rejected"
|
||||
case "context_length_exceeded", "max_tokens_exceeded", "input_too_long", "request_too_large":
|
||||
category = "summary_provider_limit"
|
||||
case "rate_limit_error", "rate_limit_exceeded", "resource_exhausted":
|
||||
category = "summary_rate_limited"
|
||||
case "deadline_exceeded", "timeout_error":
|
||||
category = "summary_timeout"
|
||||
}
|
||||
}
|
||||
}
|
||||
return generation.ProviderFailure(category)
|
||||
}
|
||||
Reference in New Issue
Block a user