浏览代码

Fixes KeyError: 'content' when using stream=False (#4944)

### 🛠 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)
tags/v0.17.0
Peterson Alves 8 个月前
父节点
当前提交
042f4c90c6
没有帐户链接到提交者的电子邮件
共有 1 个文件被更改,包括 2 次插入2 次删除
  1. 2
    2
      api/db/services/dialog_service.py

+ 2
- 2
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

正在加载...
取消
保存