From 042f4c90c6bf59b9beaf491e9c398ceaf4ae54ae Mon Sep 17 00:00:00 2001 From: Peterson Alves Date: Thu, 13 Feb 2025 23:27:01 -0300 Subject: [PATCH] Fixes KeyError: 'content' when using stream=False (#4944) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### 🛠 Fixes `KeyError: 'content'` when using `stream=False` #### 🔍 Problem When calling the chat API with `stream=False`, the code attempts to access `msg[-1]["content"]` without verifying if the key exists. This causes a `KeyError` when the message structure does not contain `"content"`. This issue was discussed in [#4885](https://github.com/infiniflow/ragflow/issues/4885), where we analyzed the root cause. The error does not occur with `stream=True`, as the response is processed differently. #### ✅ Solution - **Logging Fix:** - Before accessing `msg[-1]["content"]`, we check if the key exists. - If it does not exist, a default value (`"[content not available]"`) is used to prevent errors. - **Structural Fix in `msg` Construction:** - Ensured that every message in `msg` contains the `"content"` key, even if empty. - This fixes the issue at its root and ensures consistent behavior between `stream=True` and `stream=False`. #### 🔄 Impact - Prevents the `KeyError` without affecting normal application flow. - Ensures the integrity of the `msg` structure, avoiding future failures. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --- api/db/services/dialog_service.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/api/db/services/dialog_service.py b/api/db/services/dialog_service.py index e30bfedd8..d3993b63d 100644 --- a/api/db/services/dialog_service.py +++ b/api/db/services/dialog_service.py @@ -372,8 +372,8 @@ def chat(dialog, messages, stream=True, **kwargs): yield decorate_answer(answer) else: answer = chat_mdl.chat(prompt, msg[1:], gen_conf) - logging.debug("User: {}|Assistant: {}".format( - msg[-1]["content"], answer)) + user_content = msg[-1].get("content", "[content not available]") + logging.debug("User: {}|Assistant: {}".format(user_content, answer)) res = decorate_answer(answer) res["audio_binary"] = tts(tts_mdl, answer) yield res