RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(sdk): preserve agent answer references (#19365)
Wenchao An099e4580a05a
diff --git a/sdk/python/ragflow_sdk/modules/session.py b/sdk/python/ragflow_sdk/modules/session.pyindex 9cbd5d9c34..ef3b7a5e2b 100644--- a/sdk/python/ragflow_sdk/modules/session.py+++ b/sdk/python/ragflow_sdk/modules/session.py@@ -121,13 +121,22 @@ class Session(Base):continue # Skip lines that are not valid JSONevent = json_data.get("event", None)- if event and event != "message":- continue+ if event:+ if self.__session_type == "agent" and event not in {"message", "message_end"}:+ continue+ if self.__session_type == "chat" and event != "message":+ continue- if (self.__session_type == "agent" and event == "message_end") or (self.__session_type == "chat" and json_data.get("data") is True):+ if self.__session_type == "chat" and json_data.get("data") is True:returnif self.__session_type == "agent":- yield self._structure_answer(json_data)+ message = self._structure_answer(json_data)+ if event == "message_end":+ message.content = ""+ if message.reference:+ yield message+ continue+ yield messageelse:yield self._structure_answer(json_data["data"])else:@@ -139,15 +148,23 @@ class Session(Base):def _structure_answer(self, json_data):answer = ""+ event = Noneif self.__session_type == "agent":- answer = json_data["data"]["content"]+ event = json_data.get("event")+ json_data = json_data["data"]+ answer = json_data.get("content", "")elif self.__session_type == "chat":answer = json_data["answer"]reference = json_data.get("reference", {})temp_dict = {"content": answer, "role": "assistant"}if reference and "chunks" in reference:chunks = reference["chunks"]+ if isinstance(chunks, dict):+ chunks = list(chunks.values())temp_dict["reference"] = chunks+ if self.__session_type == "agent":+ reference_count = len(chunks) if isinstance(chunks, list) else 0+ logger.debug("Session.ask parsed agent references session_id=%s event=%s reference_count=%s", self.id, event, reference_count)message = Message(self.rag, temp_dict)return messagediff --git a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.pyindex 1e0ded1576..08fb241162 100644--- a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py+++ b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py@@ -32,6 +32,14 @@ class _DummyStreamResponse:yield line+class _DummyJsonResponse:+ def __init__(self, payload):+ self._payload = payload++ def json(self):+ return self._payload++@pytest.mark.usefixtures("clear_session_with_chat_assistants")class TestSessionWithChatAssistantCreate:@pytest.mark.p3@@ -156,3 +164,54 @@ def test_session_module_streaming_and_helper_paths_unit(monkeypatch):assert calls[1][2]["openai-compatible"] is Falseassert calls[1][2]["top_p"] == 0.8assert calls[1][3] is True+++def test_agent_session_preserves_non_stream_reference_chunks(monkeypatch, caplog):+ first_chunk = {"id": "chunk-1", "content": "first source"}+ second_chunk = {"id": "chunk-2", "content": "second source"}+ session = Session(None, {"id": "session-agent", "agent_id": "agent-1"})+ response = _DummyJsonResponse(+ {+ "data": {+ "event": "message_end",+ "data": {+ "content": "agent-answer",+ "reference": {"chunks": {"500": first_chunk, "100": second_chunk}},+ },+ }+ }+ )+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)++ with caplog.at_level("DEBUG", logger="ragflow_sdk.modules.session"):+ messages = list(session.ask("hello agent", stream=False))++ assert len(messages) == 1+ assert messages[0].content == "agent-answer"+ assert messages[0].reference == [first_chunk, second_chunk]+ assert "session_id=session-agent event=message_end reference_count=2" in caplog.text+ assert "first source" not in caplog.text+ assert "second source" not in caplog.text+++def test_agent_session_streams_all_message_references_without_duplicate_content(monkeypatch):+ first_chunk = {"id": "chunk-1", "content": "first source"}+ second_chunk = {"id": "chunk-2", "content": "second source"}+ session = Session(None, {"id": "session-agent", "agent_id": "agent-1"})+ response = _DummyStreamResponse(+ [+ 'data: {"event":"message","data":{"content":"first answer"}}',+ 'data: {"event":"message_end","data":{"content":"first answer","reference":{"chunks":{"123":{"id":"chunk-1","content":"first source"}}}}}',+ 'data: {"event":"message","data":{"content":"second answer"}}',+ 'data: {"event":"message_end","data":{"content":"second answer","reference":{"chunks":{"456":{"id":"chunk-2","content":"second source"}}}}}',+ "data: [DONE]",+ ]+ )+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)++ messages = list(session.ask("hello agent", stream=True))++ assert "".join(message.content for message in messages) == "first answersecond answer"+ assert [message.reference for message in messages if message.reference] == [[first_chunk], [second_chunk]]