Skip to content

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

fix(sdk-chat): validate chat configuration (#21732)

Sbaaoui Idriss0382485b617c
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 47541307de..2b7da9c7ce 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -21,6 +21,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "math"
"ragflow/internal/agentic_rag"
"ragflow/internal/common"
"ragflow/internal/entity"
@@ -212,6 +213,15 @@ func (s *ChatService) Create(ctx context.Context, userID string, req map[string]
if err := NormalizeSimilarityWeights(req); err != nil {
return nil, common.CodeDataError, err
}
+ if value, exists := req["llm_setting"]; exists && value != nil {
+ setting, ok := mapFromValue(value)
+ if !ok {
+ return nil, common.CodeDataError, errors.New("`llm_setting` should be an object")
+ }
+ if err := validateChatLLMSetting(setting); err != nil {
+ return nil, common.CodeDataError, err
+ }
+ }
datasetIDsValue, hasDatasetIDs := req["dataset_ids"]
if !hasDatasetIDs {
@@ -901,6 +911,9 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
if !ok {
return nil, errors.New("`llm_setting` should be an object")
}
+ if err := validateChatLLMSetting(setting); err != nil {
+ return nil, err
+ }
llmSetting = setting
}
@@ -1014,6 +1027,25 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
}
func validatePromptConfigParameters(promptConfig map[string]interface{}) error {
+ for _, field := range []string{"empty_response", "prologue", "system"} {
+ if value, exists := promptConfig[field]; exists {
+ if _, ok := value.(string); !ok {
+ return fmt.Errorf("`prompt_config.%s` should be a string", field)
+ }
+ }
+ }
+ if value, exists := promptConfig["quote"]; exists {
+ if _, ok := value.(bool); !ok {
+ return errors.New("`prompt_config.quote` should be a boolean")
+ }
+ }
+ if value, exists := promptConfig["parameters"]; exists {
+ switch value.(type) {
+ case []interface{}, []map[string]interface{}:
+ default:
+ return errors.New("`prompt_config.parameters` should be a list")
+ }
+ }
if _, err := agentic_rag.ParseOverride(promptConfig["agentic_rag"]); err != nil {
return err
}
@@ -1040,6 +1072,35 @@ func validatePromptConfigParameters(promptConfig map[string]interface{}) error {
return nil
}
+func validateChatLLMSetting(setting map[string]interface{}) error {
+ for _, field := range []string{"temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens"} {
+ value, exists := setting[field]
+ if !exists {
+ continue
+ }
+ var number float64
+ switch typed := value.(type) {
+ case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
+ case float32:
+ number = float64(typed)
+ case float64:
+ number = typed
+ case json.Number:
+ var err error
+ number, err = typed.Float64()
+ if err != nil {
+ return fmt.Errorf("`llm_setting.%s` should be a finite number", field)
+ }
+ default:
+ return fmt.Errorf("`llm_setting.%s` should be a number", field)
+ }
+ if math.IsNaN(number) || math.IsInf(number, 0) {
+ return fmt.Errorf("`llm_setting.%s` should be a finite number", field)
+ }
+ }
+ return nil
+}
+
func validateRESTChatName(value interface{}, required bool) (string, bool, error) {
if value == nil {
if required {
@@ -1172,6 +1233,12 @@ func mergeJSONMap(base entity.JSONMap, patch map[string]interface{}) entity.JSON
merged[key] = value
}
for key, value := range patch {
+ // Agentic RAG overrides replace the whole override so omitted keys inherit defaults.
+ if object, ok := mapFromValue(value); ok && key != "agentic_rag" {
+ if previous, ok := mapFromValue(merged[key]); ok {
+ value = mergeJSONMap(entity.JSONMap(previous), object)
+ }
+ }
merged[key] = value
}
return merged
diff --git a/internal/service/chat_sdk_contract_test.go b/internal/service/chat_sdk_contract_test.go
new file mode 100644
index 0000000000..d24342f8c2
--- /dev/null
+++ b/internal/service/chat_sdk_contract_test.go
@@ -0,0 +1,70 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package service
+
+import (
+ "ragflow/internal/entity"
+ "reflect"
+ "testing"
+)
+
+func TestChatConfigurationRejectsInvalidTypes(t *testing.T) {
+ for _, operation := range []string{"create", "patch"} {
+ for _, payload := range []map[string]any{
+ {"llm_setting": "invalid"},
+ {"llm_setting": map[string]any{"temperature": "bad"}},
+ {"llm_setting": map[string]any{"top_p": true}},
+ {"llm_setting": map[string]any{"presence_penalty": nil}},
+ {"llm_setting": map[string]any{"frequency_penalty": []any{}}},
+ {"llm_setting": map[string]any{"max_tokens": "1024"}},
+ {"prompt_config": map[string]any{"empty_response": 123}},
+ {"prompt_config": map[string]any{"prologue": true}},
+ {"prompt_config": map[string]any{"system": nil}},
+ {"prompt_config": map[string]any{"parameters": "invalid"}},
+ {"prompt_config": map[string]any{"quote": "invalid"}},
+ } {
+ t.Run(operation, func(t *testing.T) {
+ db := setupChatRESTUpdateServiceTestDB(t)
+ svc := NewChatService()
+ ctx := serviceTestContext(t, "user-1", "user-1")
+ var err error
+ if operation == "create" {
+ payload["name"] = "validation"
+ _, _, err = svc.Create(ctx, "user-1", payload)
+ } else {
+ createChatRESTUpdateServiceTestChat(t, db, "chat", "user-1")
+ _, err = svc.PatchChat(ctx, "user-1", "chat", payload)
+ }
+ if err == nil {
+ t.Fatalf("accepted invalid configuration: %#v", payload)
+ }
+ })
+ }
+ }
+}
+
+func TestMergeChatConfigurationPreservesNestedValues(t *testing.T) {
+ base := entity.JSONMap{"reference_metadata": map[string]any{"include": false, "fields": []any{"source"}}, "system": "preserved"}
+ merged := mergeJSONMap(base, map[string]any{"reference_metadata": map[string]any{"include": true}})
+ want := map[string]any{"include": true, "fields": []any{"source"}}
+ if !reflect.DeepEqual(merged["reference_metadata"], entity.JSONMap(want)) && !reflect.DeepEqual(merged["reference_metadata"], want) {
+ t.Fatalf("nested configuration=%#v", merged)
+ }
+ if merged["system"] != "preserved" || base["reference_metadata"].(map[string]any)["include"] != false {
+ t.Fatalf("merge lost unrelated data or mutated base")
+ }
+}
diff --git a/test/api/chat_api_test.go b/test/api/chat_api_test.go
index 1e6ae1a903..6574bd0a00 100644
--- a/test/api/chat_api_test.go
+++ b/test/api/chat_api_test.go
@@ -349,13 +349,14 @@ func TestRESTChatConfigurationMatrices(t *testing.T) {
reject bool
}
var scenarios []scenario
- for _, field := range []string{"temperature", "top_p", "presence_penalty", "frequency_penalty", "max_token"} {
- values := []any{0, 1, -1, 10, "a"}
- if field == "max_token" {
+ for _, field := range []string{"temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens"} {
+ values := []any{0, 1, -1, 10, "a", "0.5", nil, true, []any{}, apiObject{}}
+ if field == "max_tokens" {
values[1] = 1024
}
for _, value := range values {
- scenarios = append(scenarios, scenario{"llm/" + field + "/" + fmt.Sprint(value), "llm_setting", apiObject{field: value}, apiObject{field: normalizeChatNumber(value)}, false})
+ _, numeric := value.(int)
+ scenarios = append(scenarios, scenario{"llm/" + field + "/" + fmt.Sprint(value), "llm_setting", apiObject{field: value}, apiObject{field: normalizeChatNumber(value)}, !numeric})
}
}
scenarios = append(scenarios, scenario{"llm/unknown_key", "llm_setting", apiObject{"unknown": "unknown"}, apiObject{"unknown": "unknown"}, false})
@@ -378,7 +379,8 @@ func TestRESTChatConfigurationMatrices(t *testing.T) {
values = []any{"Hello World {knowledge}", "{knowledge}", "!@#$%^&*() {knowledge}", "中文测试 {knowledge}", "Hello World", 123, true}
}
for _, value := range values {
- scenarios = append(scenarios, scenario{"prompt/" + field + "/" + fmt.Sprint(value), "prompt_config", apiObject{field: value}, apiObject{field: normalizeChatNumber(value)}, false})
+ _, text := value.(string)
+ scenarios = append(scenarios, scenario{"prompt/" + field + "/" + fmt.Sprint(value), "prompt_config", apiObject{field: value}, apiObject{field: normalizeChatNumber(value)}, !text})
}
}
for _, value := range []bool{true, false} {
@@ -402,6 +404,8 @@ func TestRESTChatConfigurationMatrices(t *testing.T) {
body["dataset_ids"] = []any{}
if tc.reject {
restCode(t, restCall(t, TestConfig, http.MethodPost, "/chats", body, nil), 200, 102)
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"name": body["name"]}))["data"])
+ assertChatValue(t, data["chats"], []any{})
return
}
persisted = createRESTChat(t, body)
diff --git a/test/testcases/test_sdk_api/test_chat_assistant_management/test_create_chat_assistant.py b/test/testcases/test_sdk_api/test_chat_assistant_management/test_create_chat_assistant.py
index 187242a5ab..0dcedc867d 100644
--- a/test/testcases/test_sdk_api/test_chat_assistant_management/test_create_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_chat_assistant_management/test_create_chat_assistant.py
@@ -139,14 +139,12 @@ def test_llm_setting(chat_factory, client, llm_setting):
{"max_tokens": "invalid"},
],
)
[email protected](reason="Go ChatService.Create accepts invalid generation parameter types without validation")
def test_invalid_llm_setting(chat_factory, llm_setting):
with pytest.raises(Exception, match="llm_setting"):
chat_factory(llm_setting=llm_setting)
@pytest.mark.p3
[email protected](reason="Go ChatService.Create discards non-object llm_setting rather than rejecting it")
def test_create_rejects_invalid_llm_setting_object(client):
response = client.post("/chats", {"name": f"sdk-chat-{uuid4().hex}", "llm_setting": "invalid"}).json()
try:
@@ -216,7 +214,6 @@ def test_prompt_config(chat_factory, client, prompt_config):
{"quote": "invalid"},
],
)
[email protected](reason="Go validatePromptConfigParameters only checks duplicate keys; Create persists invalid prompt field types")
def test_invalid_prompt_fields(chat_factory, prompt_config):
with pytest.raises(Exception, match="prompt_config"):
chat_factory(prompt_config=prompt_config)
diff --git a/test/testcases/test_sdk_api/test_chat_assistant_management/test_update_chat_assistant.py b/test/testcases/test_sdk_api/test_chat_assistant_management/test_update_chat_assistant.py
index 781f64b212..226a3f27a7 100644
--- a/test/testcases/test_sdk_api/test_chat_assistant_management/test_update_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_chat_assistant_management/test_update_chat_assistant.py
@@ -156,7 +156,6 @@ def test_llm_setting(client, chat_factory, setting):
[
pytest.param(
field,
- marks=pytest.mark.skip(reason="Go PATCH persists string-valued numeric llm_setting fields (internal/service/chat.go:updateChatREST)"),
)
for field in (
"temperature",
@@ -263,7 +262,6 @@ def test_prompt_config(client, chat_factory, prompt_config):
field,
value,
id=f"{field}-{value}",
- marks=pytest.mark.skip(reason="Go PATCH merges prompt_config without validating documented string fields (internal/service/chat.go:updateChatREST)"),
)
for field, values in (
("empty_response", (123, True)),
@@ -282,7 +280,6 @@ def test_prompt_config_rejects_invalid_text(client, chat_factory, field, value):
@pytest.mark.p3
[email protected](reason="Go PATCH replaces nested prompt_config.reference_metadata instead of deep-merging it (internal/service/chat.go:mergeJSONMap)")
def test_prompt_config_preserves_nested_reference_metadata(client, chat_factory):
chat = chat_factory(prompt_config={"reference_metadata": {"include": False, "fields": ["source"]}})
before = client.get_chat(chat.id).prompt_config.reference_metadata.to_json()