Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Fix: parse api_key and group_id in Minimax config (#21289)

Lynnd61fabaf99d2
diff --git a/internal/entity/models/minimax.go b/internal/entity/models/minimax.go
index f21ca6b834..f9542ab9bf 100644
--- a/internal/entity/models/minimax.go
+++ b/internal/entity/models/minimax.go
@@ -25,6 +25,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"ragflow/internal/common"
"strings"
)
@@ -34,6 +35,33 @@ type MinimaxModel struct {
baseModel BaseModel
}
+// minimaxCredentials extracts the API key and group ID from the stored
+// api_key. When a group ID is set, the model settings form stores api_key as
+// a JSON object:
+//
+// {"api_key": "...", "group_id": "..."}
+//
+// Otherwise api_key is the plain key and no group ID is sent. MiniMax
+// authenticates the group through the GroupId query parameter, so a bundle
+// that is never unwrapped sends the whole JSON object as the Bearer token and
+// every call fails authentication.
+func minimaxCredentials(apiConfig *APIConfig) (apiKey, groupID string) {
+ if apiConfig == nil || apiConfig.ApiKey == nil {
+ return "", ""
+ }
+ key := strings.TrimSpace(*apiConfig.ApiKey)
+ if strings.HasPrefix(key, "{") {
+ var bundle struct {
+ APIKey string `json:"api_key"`
+ GroupID string `json:"group_id"`
+ }
+ if err := json.Unmarshal([]byte(key), &bundle); err == nil {
+ return strings.TrimSpace(bundle.APIKey), strings.TrimSpace(bundle.GroupID)
+ }
+ }
+ return key, ""
+}
+
// NewMinimaxModel creates a new Minimax model instance
func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxModel {
return &MinimaxModel{
@@ -41,10 +69,48 @@ func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxMod
BaseURL: baseURL,
URLSuffix: urlSuffix,
httpClient: common.GetSSRFHTTPClient(),
+ // The Bearer token is the bundle's api_key, not the stored
+ // JSON object.
+ authHeader: func(cfg *APIConfig) (string, string) {
+ apiKey, _ := minimaxCredentials(cfg)
+ return "Authorization", "Bearer " + apiKey
+ },
},
}
}
+// APIConfigCheck requires the bundle's api_key, not the raw stored value, so
+// an instance that only filled in the group ID fails here instead of sending
+// an empty Bearer token.
+func (m *MinimaxModel) APIConfigCheck(apiConfig *APIConfig) error {
+ if m.baseModel.AllowEmptyAPIKey {
+ return nil
+ }
+ apiKey, _ := minimaxCredentials(apiConfig)
+ if apiKey == "" {
+ return fmt.Errorf("api key is required")
+ }
+ return nil
+}
+
+// endpointURL resolves suffix against the configured base URL and attaches the
+// GroupId query parameter when the stored credentials carry one.
+func (m *MinimaxModel) endpointURL(apiConfig *APIConfig, suffix string) (string, error) {
+ endpoint, err := m.baseModel.EndpointURL(apiConfig, suffix)
+ if err != nil {
+ return "", err
+ }
+ _, groupID := minimaxCredentials(apiConfig)
+ if groupID == "" {
+ return endpoint, nil
+ }
+ separator := "?"
+ if strings.Contains(endpoint, "?") {
+ separator = "&"
+ }
+ return endpoint + separator + "GroupId=" + url.QueryEscape(groupID), nil
+}
+
func (m *MinimaxModel) NewInstance(baseURL map[string]string) ModelDriver {
return NewMinimaxModel(baseURL, m.baseModel.URLSuffix)
}
@@ -106,7 +172,7 @@ func extractMinimaxErrorBody(body []byte) string {
// ChatWithMessages sends multiple messages with roles and returns response
func (m *MinimaxModel) ChatWithMessages(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, modelUsage *common.ModelUsage) (*ChatResponse, error) {
- if err := m.baseModel.APIConfigCheck(apiConfig); err != nil {
+ if err := m.APIConfigCheck(apiConfig); err != nil {
return nil, err
}
modelName, err := validateMinimaxModelName(modelName)
@@ -117,7 +183,7 @@ func (m *MinimaxModel) ChatWithMessages(ctx context.Context, modelName string, m
return nil, fmt.Errorf("messages is empty")
}
- url, err := m.baseModel.EndpointURL(apiConfig, m.baseModel.URLSuffix.Chat)
+ url, err := m.endpointURL(apiConfig, m.baseModel.URLSuffix.Chat)
if err != nil {
return nil, err
}
@@ -162,7 +228,7 @@ func (m *MinimaxModel) ChatWithMessages(ctx context.Context, modelName string, m
// ChatStreamlyWithSender sends messages and streams response via sender function (best performance, no channel)
func (m *MinimaxModel) ChatStreamlyWithSender(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
- if err := m.baseModel.APIConfigCheck(apiConfig); err != nil {
+ if err := m.APIConfigCheck(apiConfig); err != nil {
return err
}
modelName, err := validateMinimaxModelName(modelName)
@@ -176,7 +242,7 @@ func (m *MinimaxModel) ChatStreamlyWithSender(ctx context.Context, modelName str
return fmt.Errorf("sender is required")
}
- url, err := m.baseModel.EndpointURL(apiConfig, m.baseModel.URLSuffix.Chat)
+ url, err := m.endpointURL(apiConfig, m.baseModel.URLSuffix.Chat)
if err != nil {
return err
}
@@ -262,12 +328,12 @@ func (m *MinimaxModel) Embed(ctx context.Context, modelName *string, request Emb
}
func (m *MinimaxModel) ListModels(ctx context.Context, apiConfig *APIConfig) ([]ListModelResponse, error) {
- if err := m.baseModel.APIConfigCheck(apiConfig); err != nil {
+ if err := m.APIConfigCheck(apiConfig); err != nil {
return nil, err
}
- apiKey := strings.TrimSpace(*apiConfig.ApiKey)
+ apiKey, _ := minimaxCredentials(apiConfig)
- url, err := m.baseModel.EndpointURL(apiConfig, m.baseModel.URLSuffix.Models)
+ url, err := m.endpointURL(apiConfig, m.baseModel.URLSuffix.Models)
if err != nil {
return nil, err
}
@@ -338,14 +404,15 @@ func (m *MinimaxModel) TranscribeAudioWithSender(ctx context.Context, modelName
// AudioSpeech convert text to audio
func (m *MinimaxModel) AudioSpeech(ctx context.Context, modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, modelUsage *common.ModelUsage) (*TTSResponse, error) {
- if err := m.baseModel.APIConfigCheck(apiConfig); err != nil {
+ if err := m.APIConfigCheck(apiConfig); err != nil {
return nil, err
}
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("text content is empty")
}
+ apiKey, _ := minimaxCredentials(apiConfig)
- url, err := m.baseModel.EndpointURL(apiConfig, m.baseModel.URLSuffix.TTS)
+ url, err := m.endpointURL(apiConfig, m.baseModel.URLSuffix.TTS)
if err != nil {
return nil, err
}
@@ -380,7 +447,7 @@ func (m *MinimaxModel) AudioSpeech(ctx context.Context, modelName *string, audio
}
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(*apiConfig.ApiKey)))
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
resp, err := m.baseModel.httpClient.Do(req)
if err != nil {
@@ -427,18 +494,19 @@ func (m *MinimaxModel) AudioSpeech(ctx context.Context, modelName *string, audio
}
func (m *MinimaxModel) AudioSpeechWithSender(ctx context.Context, modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
- if err := m.baseModel.APIConfigCheck(apiConfig); err != nil {
+ if err := m.APIConfigCheck(apiConfig); err != nil {
return err
}
if audioContent == nil || *audioContent == "" {
return fmt.Errorf("text content is empty")
}
+ apiKey, _ := minimaxCredentials(apiConfig)
ttsSuffix := m.baseModel.URLSuffix.TTS
if ttsSuffix == "" {
ttsSuffix = "v1/t2a_v2"
}
- url, err := m.baseModel.EndpointURL(apiConfig, ttsSuffix)
+ url, err := m.endpointURL(apiConfig, ttsSuffix)
if err != nil {
return err
}
@@ -476,7 +544,7 @@ func (m *MinimaxModel) AudioSpeechWithSender(ctx context.Context, modelName *str
}
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(*apiConfig.ApiKey)))
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
resp, err := m.baseModel.httpClient.Do(req)
if err != nil {
diff --git a/internal/entity/models/minimax_test.go b/internal/entity/models/minimax_test.go
index ad77dabdaf..5c714f2c40 100644
--- a/internal/entity/models/minimax_test.go
+++ b/internal/entity/models/minimax_test.go
@@ -65,6 +65,145 @@ func newMinimaxForTest(baseURL string) *MinimaxModel {
)
}
+func TestMinimaxCredentialsUnwrapsStoredBundle(t *testing.T) {
+ tests := []struct {
+ name string
+ stored string
+ wantKey string
+ wantGroup string
+ }{
+ {"plain key", "sk-plain", "sk-plain", ""},
+ {"padded plain key", " sk-plain ", "sk-plain", ""},
+ {"bundle", `{"api_key":"sk-bundled","group_id":"12345"}`, "sk-bundled", "12345"},
+ {"bundle without group", `{"api_key":"sk-bundled"}`, "sk-bundled", ""},
+ {"padded bundle", `{"api_key":" sk-bundled ","group_id":" 12345 "}`, "sk-bundled", "12345"},
+ {"malformed bundle", `{"api_key":`, `{"api_key":`, ""},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ stored := tt.stored
+ key, groupID := minimaxCredentials(&APIConfig{ApiKey: &stored})
+ if key != tt.wantKey {
+ t.Errorf("apiKey=%q, want %q", key, tt.wantKey)
+ }
+ if groupID != tt.wantGroup {
+ t.Errorf("groupID=%q, want %q", groupID, tt.wantGroup)
+ }
+ })
+ }
+
+ if key, groupID := minimaxCredentials(nil); key != "" || groupID != "" {
+ t.Errorf("nil config: apiKey=%q groupID=%q, want both empty", key, groupID)
+ }
+ if key, groupID := minimaxCredentials(&APIConfig{}); key != "" || groupID != "" {
+ t.Errorf("nil key: apiKey=%q groupID=%q, want both empty", key, groupID)
+ }
+}
+
+func TestMinimaxEndpointURLAppendsGroupID(t *testing.T) {
+ model := NewMinimaxModel(
+ map[string]string{"default": "https://api.minimax.chat"},
+ URLSuffix{Chat: "v1/text/chatcompletion_v2"},
+ )
+ suffix := model.baseModel.URLSuffix.Chat
+
+ plain := "sk-plain"
+ got, err := model.endpointURL(&APIConfig{ApiKey: &plain}, suffix)
+ if err != nil {
+ t.Fatalf("endpointURL: %v", err)
+ }
+ if want := "https://api.minimax.chat/v1/text/chatcompletion_v2"; got != want {
+ t.Errorf("url=%q, want %q: a plain key sends no GroupId", got, want)
+ }
+
+ bundle := `{"api_key":"sk-bundled","group_id":"12345"}`
+ got, err = model.endpointURL(&APIConfig{ApiKey: &bundle}, suffix)
+ if err != nil {
+ t.Fatalf("endpointURL: %v", err)
+ }
+ if want := "https://api.minimax.chat/v1/text/chatcompletion_v2?GroupId=12345"; got != want {
+ t.Errorf("url=%q, want %q", got, want)
+ }
+
+ // A suffix that already carries a query keeps it.
+ got, err = model.endpointURL(&APIConfig{ApiKey: &bundle}, suffix+"?beta=1")
+ if err != nil {
+ t.Fatalf("endpointURL: %v", err)
+ }
+ if want := "https://api.minimax.chat/v1/text/chatcompletion_v2?beta=1&GroupId=12345"; got != want {
+ t.Errorf("url=%q, want %q", got, want)
+ }
+
+ // A group ID is not necessarily numeric: whatever is stored has to reach
+ // the query string escaped, not break the URL.
+ email := `{"api_key":"sk-bundled","group_id":"[email protected]"}`
+ got, err = model.endpointURL(&APIConfig{ApiKey: &email}, suffix)
+ if err != nil {
+ t.Fatalf("endpointURL: %v", err)
+ }
+ if want := "https://api.minimax.chat/v1/text/chatcompletion_v2?GroupId=a%40b.com"; got != want {
+ t.Errorf("url=%q, want %q", got, want)
+ }
+}
+
+// TestMinimaxChatUnwrapsKeyBundle pins that a stored {api_key, group_id}
+// bundle is unwrapped before it is sent: the Bearer token is the api_key and
+// the group travels as the GroupId query parameter. The model settings form
+// stores that bundle whenever the group ID field is filled, and sending the
+// raw JSON object as the token made every MiniMax call fail authentication.
+func TestMinimaxChatUnwrapsKeyBundle(t *testing.T) {
+ withSSRFBypass(t)
+ srv := newMinimaxServer(t, func(t *testing.T, r *http.Request, _ map[string]interface{}, w http.ResponseWriter) {
+ if got := r.URL.Query().Get("GroupId"); got != "12345" {
+ t.Errorf("GroupId=%q, want 12345", got)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "choices": []map[string]interface{}{{
+ "message": map[string]interface{}{"content": "pong"},
+ }},
+ })
+ })
+ defer srv.Close()
+
+ apiKey := `{"api_key":"test-key","group_id":"12345"}`
+ resp, err := newMinimaxForTest(srv.URL).ChatWithMessages(
+ t.Context(),
+ "MiniMax-M3",
+ []Message{{Role: "user", Content: "ping"}},
+ &APIConfig{ApiKey: &apiKey},
+ nil,
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("ChatWithMessages: %v", err)
+ }
+ if resp.Answer == nil || *resp.Answer != "pong" {
+ t.Errorf("Answer=%v, want pong", resp.Answer)
+ }
+}
+
+func TestMinimaxListModelsUnwrapsKeyBundle(t *testing.T) {
+ withSSRFBypass(t)
+ srv := newMinimaxServer(t, func(t *testing.T, r *http.Request, _ map[string]interface{}, w http.ResponseWriter) {
+ if got := r.URL.Query().Get("GroupId"); got != "12345" {
+ t.Errorf("GroupId=%q, want 12345", got)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "data": []map[string]string{{"id": "MiniMax-M3"}},
+ })
+ })
+ defer srv.Close()
+
+ apiKey := `{"api_key":"test-key","group_id":"12345"}`
+ models, err := newMinimaxForTest(srv.URL).ListModels(t.Context(), &APIConfig{ApiKey: &apiKey})
+ if err != nil {
+ t.Fatalf("ListModels: %v", err)
+ }
+ if got := joinModelNames(models, ","); got != "MiniMax-M3" {
+ t.Errorf("models=%q", got)
+ }
+}
+
func TestMinimaxNewInstancePreservesConfig(t *testing.T) {
model := NewMinimaxModel(
map[string]string{"default": "http://old.example"},
@@ -578,6 +717,17 @@ func TestMinimaxValidatesInputs(t *testing.T) {
},
want: "api key is required",
},
+ {
+ // A bundle that only filled in the group ID must fail here
+ // instead of sending an empty Bearer token.
+ name: "bundle without api key",
+ run: func() error {
+ onlyGroup := `{"group_id":"12345"}`
+ _, err := newMinimaxForTest("http://unused").ChatWithMessages(ctx, "MiniMax-M3", []Message{{Role: "user", Content: "x"}}, &APIConfig{ApiKey: &onlyGroup}, nil, nil)
+ return err
+ },
+ want: "api key is required",
+ },
}
for _, tt := range tests {