Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(model): treat 400 as reachable in chat connection test again (#3929)
Jang Dong Ikb5fd79edf283
diff --git a/internal/handler/initialization.go b/internal/handler/initialization.goindex 51bce42cf..cb4fad89a 100644--- a/internal/handler/initialization.go+++ b/internal/handler/initialization.go@@ -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 SDKdiff --git a/internal/handler/initialization_chat_check_test.go b/internal/handler/initialization_chat_check_test.gonew file mode 100644index 000000000..653323176--- /dev/null+++ b/internal/handler/initialization_chat_check_test.go@@ -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, "认证失败")+}