fix(model): treat 400 as reachable in chat connection test again (#3929)

* fix(model): treat 400 as reachable in chat connection test again

checkChatModelConnection probes with max_tokens=1 and is meant to treat a
400 as "endpoint reachable, auth OK". It detected that by matching the
go-openai wording "status code: 400". Since #3470 the error comes from
api.HTTPError ("API request failed with status 400: ..."), so the branch
never matched and the probe reported a failure.

This shows up with reasoning models behind LiteLLM: the 1-token budget
cannot finish a message, the gateway answers 400, and Test Connection
fails although the saved model chats fine.

Match the status code via errors.As on *api.HTTPError instead of the
message text.

* test(handler): drop unused request parameter in fake chat gateway

* fix(model): report a 400 that carries an auth error as auth failure

Gemini's native API answers an invalid key with 400 INVALID_ARGUMENT /
API_KEY_INVALID. Since the connection check now treats any typed 400 as
reachable, that showed "连接正常,模型可用" for a bad key. Keep the 400 pass
only when the body does not describe a credential problem, and let
classifyConnectionError recognise those bodies so the message says
认证失败 instead of a bare 连接失败.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
main
Jang Dong Ik 2026-10-08 15:02:35 +09:00 committed by GitHub
parent a75e8e9ac0
commit b5fd79edf2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 125 additions and 4 deletions

View File

@ -22,6 +22,7 @@ import (
"github.com/Tencent/WeKnora/internal/handler/dto"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/middleware"
modelapi "github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/asr"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
@ -2047,6 +2048,27 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
})
}
// authFailureMarkers are lower-cased fragments that mark an upstream error
// body as a credential problem, whatever status code carried it.
var authFailureMarkers = []string{
"api_key_invalid", "api key not valid", "invalid api key", "invalid_api_key",
"unauthorized", "authentication",
}
// isAuthFailureBody reports whether an upstream error body describes a bad
// or missing credential. Gemini's native API answers an invalid key with
// 400 INVALID_ARGUMENT / API_KEY_INVALID, so a 400 alone does not prove the
// key was accepted.
func isAuthFailureBody(body string) bool {
b := strings.ToLower(body)
for _, m := range authFailureMarkers {
if strings.Contains(b, m) {
return true
}
}
return false
}
// classifyConnectionError maps an upstream error string to a short
// human-readable hint in Chinese. Callers should always combine the hint
// with the raw error message (e.g. fmt.Sprintf("%s:%v", hint, err)) so
@ -2055,7 +2077,7 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
// "what actually happened".
func classifyConnectionError(errMsg string) string {
switch {
case strings.Contains(errMsg, "401") || strings.Contains(errMsg, "unauthorized"):
case strings.Contains(errMsg, "401") || isAuthFailureBody(errMsg):
return "认证失败,请检查API Key"
case strings.Contains(errMsg, "403") || strings.Contains(errMsg, "forbidden"):
return "权限不足,请检查API Key权限"
@ -2089,12 +2111,19 @@ func (h *InitializationHandler) checkChatModelConnection(
_, err = chatInstance.Chat(ctx, testMessages, testOptions)
if err != nil {
errMsg := err.Error()
// 400 = endpoint reachable + auth ok, just a parameter mismatch
// (e.g. max_tokens vs max_completion_tokens). Treat as success.
if strings.Contains(errMsg, "status code: 400") {
// (e.g. max_tokens vs max_completion_tokens, or a reasoning model
// that cannot finish within the 1-token probe). Treat as success.
// Match the status code, not the message: the wording belongs to
// whichever HTTP client built the error and has changed before.
// Exception: some vendors (Gemini native) report an invalid key as
// 400, which must still fail the check.
var httpErr *modelapi.HTTPError
if stderrors.As(err, &httpErr) && httpErr.StatusCode == http.StatusBadRequest &&
!isAuthFailureBody(httpErr.Body) {
return true, "连接正常,模型可用"
}
errMsg := err.Error()
// For every other failure mode we surface a human-readable hint
// AND the upstream error verbatim. Swallowing the underlying
// message used to hide things like the actual URL the SDK

View File

@ -0,0 +1,92 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/stretchr/testify/require"
)
// fakeChatGateway answers every chat completion with the given status and body.
func fakeChatGateway(t *testing.T, status int, body string) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
t.Cleanup(srv.Close)
// The test server is a bare loopback IP; let the SSRF guard through.
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
return srv
}
func remoteChatModel(baseURL string) *types.Model {
return &types.Model{
Name: "gpt-5.6-luna",
Type: types.ModelTypeKnowledgeQA,
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: baseURL,
APIKey: "sk-test",
},
}
}
// A reasoning model behind LiteLLM cannot finish within the 1-token probe and
// the gateway answers 400. The endpoint is reachable and the key accepted, so
// the check must pass, as it did before the HTTP client changed its wording.
func TestCheckChatModelConnectionTreats400AsReachable(t *testing.T) {
srv := fakeChatGateway(t, http.StatusBadRequest,
`{"error":{"message":"litellm.BadRequestError: OpenAIException - Could not finish the message `+
`because max_tokens or model output limit was reached.","type":"invalid_request_error","code":"400"}}`)
h := &InitializationHandler{}
available, message := h.checkChatModelConnection(context.Background(), remoteChatModel(srv.URL), "", "")
require.True(t, available, "message: %s", message)
}
func TestCheckChatModelConnectionReportsAuthFailure(t *testing.T) {
srv := fakeChatGateway(t, http.StatusUnauthorized,
`{"error":{"message":"Invalid API key","type":"invalid_request_error","code":"401"}}`)
h := &InitializationHandler{}
available, message := h.checkChatModelConnection(context.Background(), remoteChatModel(srv.URL), "", "")
require.False(t, available)
require.Contains(t, message, "认证失败")
}
// Gemini's native API reports an invalid key as 400 INVALID_ARGUMENT /
// API_KEY_INVALID. That 400 is an auth failure, not "reachable".
func TestCheckChatModelConnectionReportsGeminiInvalidKey(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":{"code":400,"message":"API key not valid. Please pass a valid API key.",` +
`"status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",` +
`"reason":"API_KEY_INVALID","domain":"googleapis.com"}]}}`))
}))
t.Cleanup(srv.Close)
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
model := remoteChatModel(srv.URL)
model.Name = "gemini-2.5-flash"
model.Parameters.Provider = "gemini"
h := &InitializationHandler{}
available, message := h.checkChatModelConnection(context.Background(), model, "", "")
require.Contains(t, gotPath, ":generateContent", "probe should use the native Gemini API")
require.False(t, available, "message: %s", message)
require.Contains(t, message, "认证失败")
}