Skip to content
Closed
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. The classifier's kind decides first, so its generic `api_error` placeholder never wins; status only supplies the fallback, and a bare 404 no longer claims `model_not_found`. The API-key and console-key middleware envelopes use the same vocabulary, so a missing or wrong key reports `authentication_error` instead of `api_error`.

### 中文

- OpenAI 兼容接口的错误响应现在返回正确的 `error.type`(`invalid_request_error`、`authentication_error`、`permission_error`、`rate_limit_error`、`insufficient_quota`、`model_not_found`、`api_error`),不再统一写成泛化的 `api_error`,客户端可按错误类型正确区分额度不足、鉴权失败和限流。映射先由分类结果的 kind 决定,分类器默认填充的 `api_error` 不再抢先返回;只有 kind 无法判断时才按 HTTP 状态兜底,普通 404 不再被标成 `model_not_found`。API Key 与控制台密钥的中间件错误也改用同一套取值,密钥缺失或错误会报成 `authentication_error`。
70 changes: 69 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,81 @@ 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. Kind is authoritative because Classify derives it from the
// upstream status, body and nested kind; Type is only a hint, and it defaults
// to generic values ("api_error", "invalid_request_error") that would hide a
// rate-limit, auth or model-availability rejection. When Kind says nothing
// specific, a recognized upstream Type wins, then Status supplies the fallback.
func openaiErrorType(classified executor.Classified) string {
switch classified.Kind {
case accounts.KindModelNotAvailable:
return "model_not_found"
case accounts.KindInvalidRequest:
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"
}
switch typ := strings.TrimSpace(classified.Type); typ {
case "invalid_request_error", "authentication_error", "permission_error",
"rate_limit_error", "insufficient_quota", "model_not_found":
return typ
}
return openaiErrorTypeForStatus(classified.Status)
}

// openaiErrorTypeForStatus is the status-only fallback. 404 stays a generic
// invalid_request_error: only a classified model-availability failure earns
// model_not_found, so an unrelated missing route is not mislabelled as a
// model problem.
func openaiErrorTypeForStatus(status int) string {
switch {
case status == http.StatusUnauthorized:
return "authentication_error"
case status == http.StatusForbidden:
return "permission_error"
case status == http.StatusTooManyRequests:
return "rate_limit_error"
case status == http.StatusBadRequest || status == http.StatusNotFound ||
status == http.StatusUnprocessableEntity ||
status == http.StatusRequestEntityTooLarge:
return "invalid_request_error"
default:
return "api_error"
}
}

// OpenAIErrorTypeForStatus exposes the status-only mapping so the server
// middleware (API-key auth, console guard) writes the same error.type
// vocabulary as the public gateway instead of a hard-coded api_error.
func OpenAIErrorTypeForStatus(status int) string {
return openaiErrorTypeForStatus(status)
}

func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if s := strings.TrimSpace(v); s != "" {
Expand Down
192 changes: 192 additions & 0 deletions internal/gateway/http_error_type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
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 maps to model_not_found", accounts.KindModelNotAvailable, http.StatusBadRequest, "", "model_not_found"},
{"unavailable 502 maps to api_error", accounts.KindUnavailable, http.StatusBadGateway, "", "api_error"},
{"recognized upstream type is ignored when kind is specific", accounts.KindQuota, http.StatusTooManyRequests, "rate_limit_error", "insufficient_quota"},
{"generic api_error must not win", accounts.KindRateLimit, http.StatusTooManyRequests, "api_error", "rate_limit_error"},
{"generic api_error on auth falls back to kind", accounts.KindAuth, http.StatusUnauthorized, "api_error", "authentication_error"},
{"specific upstream type used for unknown kind", accounts.KindUnavailable, http.StatusBadGateway, "permission_error", "permission_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: "invalid_request_error",
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 TestWriteClassifiedErrUsesRealClassifierOutput(t *testing.T) {
// These cases go through executor.Classify, not a hand-built Classified, so
// the default Type: "api_error" the classifier stamps on generic failures is
// part of the input. That default must not beat the Kind/Status mapping.
cases := []struct {
name string
upstream int
body string
wantType string
wantStatus int
}{
{"429 rate limit", http.StatusTooManyRequests, `{"error":{"message":"too many requests","code":"rate_limit_exceeded"}}`, "rate_limit_error", http.StatusTooManyRequests},
{"401 auth", http.StatusUnauthorized, `{"error":{"message":"unauthorized"}}`, "authentication_error", http.StatusUnauthorized},
{"403 auth", http.StatusForbidden, `{"error":{"message":"forbidden"}}`, "permission_error", http.StatusForbidden},
{"429 quota", http.StatusTooManyRequests, `{"error":{"message":"insufficient_quota","code":"insufficient_quota"}}`, "insufficient_quota", http.StatusTooManyRequests},
{"model not available", http.StatusNotFound, `{"error":{"message":"model_not_available","code":"model_not_available"}}`, "model_not_found", http.StatusBadRequest},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
classified := executor.Classify(tc.upstream, tc.body, "", "", "")
err := executor.NewExecutionError(classified, nil)

w := httptest.NewRecorder()
WriteClassifiedErr(w, err)
if w.Code != tc.wantStatus {
t.Fatalf("status = %d, want %d (classified=%+v)", w.Code, tc.wantStatus, classified)
}
var body struct {
Error struct {
Type string `json:"type"`
} `json:"error"`
}
if jerr := json.Unmarshal(w.Body.Bytes(), &body); jerr != nil {
t.Fatalf("decode envelope: %v", jerr)
}
if body.Error.Type != tc.wantType {
t.Fatalf("error.type = %q, want %q (classified.Type=%q kind=%q)", body.Error.Type, tc.wantType, classified.Type, classified.Kind)
}
})
}
}

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)
}
8 changes: 7 additions & 1 deletion internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package server
import (
"encoding/json"
"net/http"

"github.com/caigee-cmd/cli2api/internal/gateway"
)

func writeJSON(w http.ResponseWriter, status int, v any) {
Expand All @@ -11,11 +13,15 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
_ = json.NewEncoder(w).Encode(v)
}

// writeErr keeps the middleware envelopes (API-key auth, console guard,
// update-in-progress) on the same OpenAI error.type vocabulary as the public
// gateway. A hard-coded api_error here made the most common client failures —
// a missing or invalid key — look like generic server errors.
func writeErr(w http.ResponseWriter, status int, code, msg string) {
writeJSON(w, status, map[string]any{
"error": map[string]any{
"message": msg,
"type": "api_error",
"type": gateway.OpenAIErrorTypeForStatus(status),
"code": code,
},
})
Expand Down
45 changes: 45 additions & 0 deletions internal/server/http_error_type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package server

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)

// The middleware envelopes are the first error a client sees for the two most
// common failures (a missing key and a console-only key), so they must carry
// the same OpenAI error.type vocabulary as the public gateway.
func TestWriteErrCarriesOpenAIErrorType(t *testing.T) {
cases := []struct {
status int
code string
wantType string
}{
{http.StatusUnauthorized, "invalid_api_key", "authentication_error"},
{http.StatusForbidden, "console_key_required", "permission_error"},
{http.StatusServiceUnavailable, "service_updating", "api_error"},
}
for _, tc := range cases {
w := httptest.NewRecorder()
writeErr(w, tc.status, tc.code, "message")
if w.Code != tc.status {
t.Fatalf("status = %d, want %d", w.Code, tc.status)
}
var body struct {
Error struct {
Type string `json:"type"`
Code string `json:"code"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("decode envelope: %v", err)
}
if body.Error.Type != tc.wantType {
t.Fatalf("error.type = %q, want %q (code=%q)", body.Error.Type, tc.wantType, tc.code)
}
if body.Error.Code != tc.code {
t.Fatalf("error.code = %q, want %q", body.Error.Code, tc.code)
}
}
}
Loading