Skip to content

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

Fix: upload image to model in chat (#19257)

Lynn2f8dab219940
diff --git a/api/apps/restful_apis/agent_api.py b/api/apps/restful_apis/agent_api.py
index 05bb57d19a..4194071198 100644
--- a/api/apps/restful_apis/agent_api.py
+++ b/api/apps/restful_apis/agent_api.py
@@ -2641,7 +2641,15 @@ def _attachment_request_metadata():
async def _stream_agent_attachment(tenant_id, attachment_id, *, inline: bool):
attachment_id = attachment_id or request.view_args.get("attachment_id")
content_type, ext, filename = _attachment_request_metadata()
- data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
+ # Chat uploads are written to the per-user downloads bucket (FileService.put_blob),
+ # while agent-generated attachments are written under the bare tenant id. Probe
+ # both so this endpoint serves either; attachment ids are UUIDs, so the two
+ # buckets cannot both hold a given id.
+ data = None
+ for bucket in (f"{tenant_id}-downloads", tenant_id):
+ data = await thread_pool_exec(settings.STORAGE_IMPL.get, bucket, attachment_id)
+ if data:
+ break
if not data:
return get_data_error_result(message="document not found")
response = await make_response(data)
diff --git a/api/apps/restful_apis/chat_api.py b/api/apps/restful_apis/chat_api.py
index 3139a71cd5..8da7920204 100644
--- a/api/apps/restful_apis/chat_api.py
+++ b/api/apps/restful_apis/chat_api.py
@@ -396,12 +396,19 @@ async def _validate_dataset_ids(dataset_ids, tenant_id):
def _apply_prompt_defaults(req):
prompt_config = req.setdefault("prompt_config", {})
+ kb_ids = req.get("kb_ids") or []
for key, value in _DEFAULT_PROMPT_CONFIG.items():
temp = prompt_config.get(key)
if (key == "system" and not temp) or key not in prompt_config:
- prompt_config[key] = deepcopy(value)
+ if key == "system" and not kb_ids:
+ # No dataset bound: do not seed the dataset-oriented default system prompt.
+ # Its hard-coded "The answer you are looking for is not found in the dataset!"
+ # sentence would otherwise be sent verbatim to the model on the no-dataset path.
+ prompt_config[key] = ""
+ else:
+ prompt_config[key] = deepcopy(value)
- if req.get("kb_ids") and not prompt_config.get("parameters") and "{knowledge}" in prompt_config.get("system", ""):
+ if kb_ids and not prompt_config.get("parameters") and "{knowledge}" in prompt_config.get("system", ""):
prompt_config["parameters"] = [{"key": "knowledge", "optional": False}]
if not any(p.get("key") == "date" for p in prompt_config.get("parameters", [])):
prompt_config.setdefault("parameters", []).append({"key": "date", "optional": True})
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 37e1293847..449314a6bf 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -471,8 +471,16 @@ func applyCreatePromptDefaults(req map[string]interface{}) {
if promptConfig == nil {
promptConfig = map[string]interface{}{}
}
+ kbIDs, _ := listFromValue(req["kb_ids"])
if system, ok := promptConfig["system"]; !ok || !isTruthy(system) {
- promptConfig["system"] = pyDefaultSystemPrompt
+ if len(kbIDs) > 0 {
+ promptConfig["system"] = pyDefaultSystemPrompt
+ } else {
+ // No dataset bound: do not seed the dataset-oriented default system prompt. Its
+ // hard-coded "not found in the dataset" sentence would otherwise be sent verbatim
+ // to the model on the no-dataset chat path.
+ promptConfig["system"] = ""
+ }
}
if _, ok := promptConfig["prologue"]; !ok {
promptConfig["prologue"] = pyDefaultPrologue
@@ -493,7 +501,6 @@ func applyCreatePromptDefaults(req map[string]interface{}) {
promptConfig["refine_multiturn"] = true
}
- kbIDs, _ := listFromValue(req["kb_ids"])
system, _ := promptConfig["system"].(string)
if len(kbIDs) > 0 && !isTruthy(promptConfig["parameters"]) && strings.Contains(system, "{knowledge}") {
promptConfig["parameters"] = []interface{}{map[string]interface{}{"key": "knowledge", "optional": false}}
diff --git a/internal/service/chat_rest_update_test.go b/internal/service/chat_rest_update_test.go
index b1d418277b..9d214e8f30 100644
--- a/internal/service/chat_rest_update_test.go
+++ b/internal/service/chat_rest_update_test.go
@@ -537,8 +537,8 @@ func TestChatServiceCreatePromptDefaultsContract(t *testing.T) {
if !ok || param["key"] != "knowledge" || param["optional"] != false {
t.Fatalf("expected knowledge parameter, got %#v", params[0])
}
- if promptConfig["system"] == "" {
- t.Fatal("expected non-empty default system prompt")
+ if promptConfig["system"] != "" {
+ t.Fatalf("expected empty default system prompt without a dataset, got %#v", promptConfig["system"])
}
if promptConfig["prologue"] == "" {
t.Fatal("expected non-empty default prologue")
@@ -547,3 +547,29 @@ func TestChatServiceCreatePromptDefaultsContract(t *testing.T) {
t.Fatal("expected non-empty default empty_response")
}
}
+
+func TestChatServiceCreateWithDatasetSeedsDatasetSystemPrompt(t *testing.T) {
+ setupChatRESTUpdateServiceTestDB(t)
+
+ svc := NewChatService()
+ ctx := t.Context()
+ resp, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ "name": "prompt defaults chat with dataset",
+ "kb_ids": []interface{}{"kb-1"},
+ })
+ if err != nil {
+ t.Fatalf("Create failed: %v", err)
+ }
+ if code != common.CodeSuccess {
+ t.Fatalf("expected success code, got %d", code)
+ }
+
+ promptConfig, ok := resp["prompt_config"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected prompt_config map, got %T: %+v", resp["prompt_config"], resp["prompt_config"])
+ }
+ system, _ := promptConfig["system"].(string)
+ if system == "" || !strings.Contains(system, "{knowledge}") || !strings.Contains(system, "not found in the dataset") {
+ t.Fatalf("expected dataset-oriented default system prompt, got %#v", promptConfig["system"])
+ }
+}
diff --git a/test/testcases/restful_api/test_chats.py b/test/testcases/restful_api/test_chats.py
index 701eda4fc8..b4aeab490a 100644
--- a/test/testcases/restful_api/test_chats.py
+++ b/test/testcases/restful_api/test_chats.py
@@ -1183,7 +1183,7 @@ def test_chat_create_accepts_provider_scoped_rerank_id_unit(monkeypatch):
@pytest.mark.p1
-def test_chat_create_allows_default_knowledge_placeholder_without_sources_unit(monkeypatch):
+def test_chat_create_omits_dataset_default_prompt_without_sources_unit(monkeypatch):
module = _load_chat_routes_unit_module(monkeypatch)
saved = {}
_set_route_unit_request_json(monkeypatch, module, {"name": "chat-a"})
@@ -1201,7 +1201,9 @@ def test_chat_create_allows_default_knowledge_placeholder_without_sources_unit(m
res = _run(module.create.__wrapped__())
assert res["code"] == 0
assert saved["kb_ids"] == []
- assert saved["prompt_config"]["system"].find("{knowledge}") >= 0
+ # Without a dataset the dataset-oriented default system prompt (including its forced
+ # "not found in the dataset" sentence) must not be seeded.
+ assert saved["prompt_config"]["system"] == ""
assert saved["prompt_config"]["parameters"] == [{"key": "knowledge", "optional": False}, {"key": "date", "optional": True}]
@@ -1580,7 +1582,7 @@ def test_chat_create_prompt_contract(rest_client, clear_chats):
("prompt_config", "empty_response"): DEFAULT_CHAT_EMPTY_RESPONSE,
("prompt_config", "prologue"): DEFAULT_CHAT_PROLOGUE,
("prompt_config", "quote"): True,
- ("prompt_config", "system"): DEFAULT_CHAT_SYSTEM_PROMPT,
+ ("prompt_config", "system"): "",
},
),
("similarity_threshold zero", {"similarity_threshold": 0}, {("similarity_threshold",): 0}),
diff --git a/test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py b/test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py
index 94ecb62f29..b1bf2ee206 100644
--- a/test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py
+++ b/test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py
@@ -227,3 +227,34 @@ class TestAttachmentDownloadMissingBlob:
result = asyncio.run(module.download_attachment(tenant_id="t1", attachment_id="good"))
# SimpleNamespace from our _make_response stub
assert hasattr(result, "payload") and result.payload == b"PDFDATA"
+
+ def test_chat_upload_served_from_downloads_bucket(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Chat uploads land in '<tenant>-downloads', not the bare tenant bucket.
+
+ The endpoint is also used to preview chat attachments, which
+ FileService.put_blob writes under '<tenant>-downloads'. Reading only the
+ bare tenant id returned 'document not found' for every one of them.
+ """
+ probed = []
+
+ def storage_get(bucket, _fnm, *_args, **_kwargs):
+ probed.append(bucket)
+ return b"CHATUPLOAD" if bucket == "t1-downloads" else None
+
+ module = _load_agent_api(monkeypatch, storage_get=storage_get)
+ result = asyncio.run(module.download_attachment(tenant_id="t1", attachment_id="chat-upload"))
+ assert hasattr(result, "payload") and result.payload == b"CHATUPLOAD"
+ assert probed == ["t1-downloads"]
+
+ def test_agent_attachment_falls_back_to_bare_tenant(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Agent-generated attachments live under the bare tenant id."""
+ probed = []
+
+ def storage_get(bucket, _fnm, *_args, **_kwargs):
+ probed.append(bucket)
+ return b"AGENTDOC" if bucket == "t1" else None
+
+ module = _load_agent_api(monkeypatch, storage_get=storage_get)
+ result = asyncio.run(module.download_attachment(tenant_id="t1", attachment_id="agent-doc"))
+ assert hasattr(result, "payload") and result.payload == b"AGENTDOC"
+ assert probed == ["t1-downloads", "t1"]