From 4c7596abd7d624046fd0d26575a3657a7f92909b Mon Sep 17 00:00:00 2001 From: guyu233 Date: Fri, 4 Dec 2026 15:17:10 +0800 Subject: [PATCH] fix(gateway): report the OpenAI error.type for classified failures Classified failures previously all surfaced as api_error even though clients branch on error.type. Map recognized upstream types first, then Kind, then Status, and use the same mapping for the SSE structured error frame. Retroactively correct: invalid request, auth, permission, quota, rate limit, and model-not-found cases. --- .../unreleased/openai-error-type-mapping.md | 7 + internal/gateway/http.go | 59 ++++++- internal/gateway/http_error_type_test.go | 147 ++++++++++++++++++ internal/gateway/openai_stream.go | 2 +- internal/gateway/usage.go | 2 +- 5 files changed, 214 insertions(+), 3 deletions(-) create mode 100644 changelog/unreleased/openai-error-type-mapping.md create mode 100644 internal/gateway/http_error_type_test.go diff --git a/changelog/unreleased/openai-error-type-mapping.md b/changelog/unreleased/openai-error-type-mapping.md new file mode 100644 index 000000000..7904c718b --- /dev/null +++ b/changelog/unreleased/openai-error-type-mapping.md @@ -0,0 +1,7 @@ +### English + +- OpenAI-compatible error responses now report the correct `error.type` (`invalid_request_error`, `authentication_error`, `permission_error`, `rate_limit_error`, `insufficient_quota`, `model_not_found`, or `api_error`) instead of a generic `api_error`, so clients that branch on error type classify quota, auth, and rate-limit failures correctly. + +### 中文 + +- OpenAI 兼容接口的错误响应现在返回正确的 `error.type`(`invalid_request_error`、`authentication_error`、`permission_error`、`rate_limit_error`、`insufficient_quota`、`model_not_found`、`api_error`),不再统一写成泛化的 `api_error`,客户端可按错误类型正确区分额度不足、鉴权失败和限流。 diff --git a/internal/gateway/http.go b/internal/gateway/http.go index 3521b0fd9..b219407d6 100644 --- a/internal/gateway/http.go +++ b/internal/gateway/http.go @@ -4,6 +4,9 @@ import ( "encoding/json" "net/http" "strings" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" ) func writeJSON(w http.ResponseWriter, status int, v any) { @@ -12,16 +15,70 @@ func writeJSON(w http.ResponseWriter, status int, v any) { _ = json.NewEncoder(w).Encode(v) } +// writeErr builds a plain OpenAI-style error envelope. The error type follows +// the HTTP status so a bare status-only failure still carries a meaningful +// type; callers holding a Classified use writeTypedErr with openaiErrorType. func writeErr(w http.ResponseWriter, status int, code, msg string) { + writeTypedErr(w, status, openaiErrorTypeForStatus(status), code, msg) +} + +func writeTypedErr(w http.ResponseWriter, status int, errType, code, msg string) { writeJSON(w, status, map[string]any{ "error": map[string]any{ "message": msg, - "type": "api_error", + "type": errType, "code": code, }, }) } +// openaiErrorType maps a classified failure onto the OpenAI error.type +// vocabulary. A recognized upstream type wins; otherwise Kind, then Status, +// supply the fallback. Clients branch on error.type (not only on code), so a +// quota or auth rejection must not surface as a generic api_error. +func openaiErrorType(classified executor.Classified) string { + switch strings.TrimSpace(classified.Type) { + case "invalid_request_error", "authentication_error", "permission_error", + "rate_limit_error", "insufficient_quota", "model_not_found", "api_error": + return classified.Type + } + switch classified.Kind { + case accounts.KindInvalidRequest, accounts.KindModelNotAvailable: + if classified.Status == http.StatusNotFound { + return "model_not_found" + } + return "invalid_request_error" + case accounts.KindAuth: + if classified.Status == http.StatusForbidden { + return "permission_error" + } + return "authentication_error" + case accounts.KindQuota: + return "insufficient_quota" + case accounts.KindRateLimit: + return "rate_limit_error" + } + return openaiErrorTypeForStatus(classified.Status) +} + +func openaiErrorTypeForStatus(status int) string { + switch { + case status == http.StatusUnauthorized: + return "authentication_error" + case status == http.StatusForbidden: + return "permission_error" + case status == http.StatusNotFound: + return "model_not_found" + case status == http.StatusTooManyRequests: + return "rate_limit_error" + case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity || + status == http.StatusRequestEntityTooLarge: + return "invalid_request_error" + default: + return "api_error" + } +} + func firstNonEmpty(vals ...string) string { for _, v := range vals { if s := strings.TrimSpace(v); s != "" { diff --git a/internal/gateway/http_error_type_test.go b/internal/gateway/http_error_type_test.go new file mode 100644 index 000000000..3cebb8fc9 --- /dev/null +++ b/internal/gateway/http_error_type_test.go @@ -0,0 +1,147 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" +) + +func TestOpenAIErrorTypeMapping(t *testing.T) { + cases := []struct { + name string + kind string + status int + typ string + wantType string + }{ + {"quota maps to insufficient_quota", accounts.KindQuota, http.StatusTooManyRequests, "", "insufficient_quota"}, + {"auth 401 maps to authentication_error", accounts.KindAuth, http.StatusUnauthorized, "", "authentication_error"}, + {"auth 403 maps to permission_error", accounts.KindAuth, http.StatusForbidden, "", "permission_error"}, + {"rate limit maps to rate_limit_error", accounts.KindRateLimit, http.StatusTooManyRequests, "", "rate_limit_error"}, + {"invalid request maps to invalid_request_error", accounts.KindInvalidRequest, http.StatusBadRequest, "", "invalid_request_error"}, + {"model not available 404 maps to model_not_found", accounts.KindModelNotAvailable, http.StatusNotFound, "", "model_not_found"}, + {"unavailable 502 maps to api_error", accounts.KindUnavailable, http.StatusBadGateway, "", "api_error"}, + {"recognized upstream type wins over kind", accounts.KindQuota, http.StatusTooManyRequests, "rate_limit_error", "rate_limit_error"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classified{Kind: tc.kind, Status: tc.status, Type: tc.typ} + if got := openaiErrorType(classified); got != tc.wantType { + t.Fatalf("openaiErrorType(%+v) = %q, want %q", classified, got, tc.wantType) + } + }) + } +} + +func TestOpenAIErrorTypeForStatus(t *testing.T) { + cases := map[int]string{ + http.StatusUnauthorized: "authentication_error", + http.StatusForbidden: "permission_error", + http.StatusNotFound: "model_not_found", + http.StatusTooManyRequests: "rate_limit_error", + http.StatusBadRequest: "invalid_request_error", + http.StatusUnprocessableEntity: "invalid_request_error", + http.StatusRequestEntityTooLarge: "invalid_request_error", + http.StatusBadGateway: "api_error", + http.StatusInternalServerError: "api_error", + } + for status, want := range cases { + if got := openaiErrorTypeForStatus(status); got != want { + t.Fatalf("openaiErrorTypeForStatus(%d) = %q, want %q", status, got, want) + } + } +} + +func TestWriteClassifiedErrEnvelopeCarriesTypeAndRetryAfter(t *testing.T) { + classified := executor.Classified{ + Kind: accounts.KindQuota, + Status: http.StatusTooManyRequests, + Code: "insufficient_quota", + Message: "upstream diagnostic that must not reach the client", + RetryAfter: 45 * time.Second, + } + err := executor.NewExecutionError(classified, nil) + + w := httptest.NewRecorder() + WriteClassifiedErr(w, err) + + if w.Code != http.StatusTooManyRequests { + t.Fatalf("status = %d, want %d", w.Code, http.StatusTooManyRequests) + } + if got := w.Header().Get("Retry-After"); got != "45" { + t.Fatalf("Retry-After = %q, want 45", got) + } + + var body struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode error envelope: %v", err) + } + if body.Error.Type != "insufficient_quota" { + t.Fatalf("error.type = %q, want insufficient_quota", body.Error.Type) + } + if body.Error.Code != "insufficient_quota" { + t.Fatalf("error.code = %q, want insufficient_quota", body.Error.Code) + } +} + +func TestStructuredStreamErrorCarriesMappedType(t *testing.T) { + cases := []struct { + name string + kind string + status int + wantType string + }{ + {name: "quota", kind: accounts.KindQuota, status: http.StatusTooManyRequests, wantType: "insufficient_quota"}, + {name: "rate limit", kind: accounts.KindRateLimit, status: http.StatusTooManyRequests, wantType: "rate_limit_error"}, + {name: "auth", kind: accounts.KindAuth, status: http.StatusUnauthorized, wantType: "authentication_error"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classified{ + Kind: tc.kind, + Status: tc.status, + Code: "test_code", + } + err := executor.NewExecutionError(classified, nil) + var buf bytes.Buffer + if werr := writeStructuredStreamError(&buf, err); werr != nil { + t.Fatalf("writeStructuredStreamError: %v", werr) + } + var dataLine string + for _, line := range strings.Split(buf.String(), "\n") { + if strings.HasPrefix(line, "data:") { + dataLine = strings.TrimSpace(strings.TrimPrefix(line, "data:")) + } + } + var envelope struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Kind string `json:"kind"` + } `json:"error"` + } + if jerr := json.Unmarshal([]byte(dataLine), &envelope); jerr != nil { + t.Fatalf("decode stream error payload: %v", jerr) + } + if envelope.Error.Type != tc.wantType { + t.Fatalf("error.type = %q, want %q", envelope.Error.Type, tc.wantType) + } + if envelope.Error.Kind != tc.kind { + t.Fatalf("error.kind = %q, want %q", envelope.Error.Kind, tc.kind) + } + }) + } +} diff --git a/internal/gateway/openai_stream.go b/internal/gateway/openai_stream.go index 8071cc2ff..91adbf03f 100644 --- a/internal/gateway/openai_stream.go +++ b/internal/gateway/openai_stream.go @@ -259,7 +259,7 @@ func writeStructuredStreamError(writer io.Writer, err error) error { status = http.StatusBadGateway } code := firstNonEmpty(classified.Code, "upstream_error") - typ := firstNonEmpty(classified.Type, "api_error") + typ := openaiErrorType(classified) message := firstNonEmpty(classified.Message, code) errorPayload := map[string]any{ "message": message, diff --git a/internal/gateway/usage.go b/internal/gateway/usage.go index 00496f2b1..d0e406932 100644 --- a/internal/gateway/usage.go +++ b/internal/gateway/usage.go @@ -59,5 +59,5 @@ func WriteClassifiedErr(w http.ResponseWriter, err error) { } else { w.Header().Set("X-Qoder-Failover", "0") } - writeErr(w, classified.Status, classified.Code, classified.Message) + writeTypedErr(w, classified.Status, openaiErrorType(classified), classified.Code, classified.Message) }