Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix: handle thinking stream edge cases (unclosed tags + missing done)

lyingbuge5c46642e90b
diff --git a/internal/application/service/chat_pipline/chat_completion_stream.go b/internal/application/service/chat_pipline/chat_completion_stream.go
index f618d6c97..d2e671514 100644
--- a/internal/application/service/chat_pipline/chat_completion_stream.go
+++ b/internal/application/service/chat_pipline/chat_completion_stream.go
@@ -188,6 +188,24 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
}
}
+ // Compensate for unclosed <think> tag when stream ends unexpectedly
+ // (e.g., context cancelled, upstream error) without an answer arriving.
+ if thinkingStarted && !thinkingEnded {
+ thinkingEnded = true
+ finalContent += "</think>"
+ if err := eventBus.Emit(ctx, types.Event{
+ ID: answerID,
+ Type: types.EventType(event.EventAgentFinalAnswer),
+ SessionID: chatManage.SessionID,
+ Data: event.AgentFinalAnswerData{
+ Content: "</think>",
+ Done: true,
+ },
+ }); err != nil {
+ logger.Errorf(ctx, "Failed to emit think close tag on stream end: %v", err)
+ }
+ }
+
pipelineInfo(ctx, "Stream", "channel_close", map[string]interface{}{
"session_id": chatManage.SessionID,
})
diff --git a/internal/models/chat/remote_api.go b/internal/models/chat/remote_api.go
index ae21f8ba6..7f076d011 100644
--- a/internal/models/chat/remote_api.go
+++ b/internal/models/chat/remote_api.go
@@ -642,6 +642,17 @@ func (c *RemoteAPIChat) processStreamDelta(ctx context.Context, choice *openai.C
ToolCalls: state.buildOrderedToolCalls(),
}
}
+
+ // Ensure thinking done is sent when stream finishes without any answer content
+ // (e.g., model only produced reasoning then hit finish_reason with empty content).
+ if isDone && state.hasThinking {
+ streamChan <- types.StreamResponse{
+ ResponseType: types.ResponseTypeThinking,
+ Content: "",
+ Done: true,
+ }
+ state.hasThinking = false
+ }
}
// processToolCallsDelta 处理 tool calls 的增量更新