Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog/unreleased/openai-error-type-mapping.md
Original file line number Diff line number Diff line change
@@ -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`,客户端可按错误类型正确区分额度不足、鉴权失败和限流。
59 changes: 58 additions & 1 deletion internal/gateway/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 != "" {
Expand Down
147 changes: 147 additions & 0 deletions internal/gateway/http_error_type_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
2 changes: 1 addition & 1 deletion internal/gateway/openai_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion internal/gateway/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Loading