From 8d2e641d052dd2e2800ad9ba5f112e010dd08979 Mon Sep 17 00:00:00 2001 From: martsforever Date: Thu, 4 Sep 2025 23:00:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20has=5Femit=5Fchunk=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/add_langgraph_chat_route.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/app/controller/add_langgraph_chat_route.py b/app/controller/add_langgraph_chat_route.py index 14c74fd..536e715 100644 --- a/app/controller/add_langgraph_chat_route.py +++ b/app/controller/add_langgraph_chat_route.py @@ -86,8 +86,14 @@ def add_langgraph_chat_route(app: FastAPI): async def generator_function(): graph = await ChatAgent.get_agent() + # chat_state = await ChatAgent.get_chat_state(thread_id) # chat_history_list = chat_state.get('messages') + + # has_emit_chunk 用来优化流式传输,避免将content为空的为AIMessageChunk发送给前端(实际上此时正在输出思考内容) + # 第一次的时候输出,后续再输出content为空的AIMessageChunk不发送给前端 + has_emit_chunk = False + async for chunk in graph.astream( stream_input, config=stream_config, @@ -108,7 +114,8 @@ def add_langgraph_chat_route(app: FastAPI): # messages模式流式输出,此时 chunk[1][0] 为AIMessageChunk chunk_message = chunk[1][0] if not chunk_message.content: - continue + if has_emit_chunk: + continue else: # updates模式流式输出 for k, v in chunk[1].items(): @@ -125,6 +132,7 @@ def add_langgraph_chat_route(app: FastAPI): "msg_type": chunk_message.type, "msg_content": chunk_message.content, } + has_emit_chunk = True if isinstance(chunk_message, AIMessage): if chunk_message.tool_calls: