index.html 5.22 KB
Newer Older
何处是我家's avatar
提交  
何处是我家 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>流式聊天Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .chat-container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            padding: 20px;
        }
        .chat-messages {
            height: 500px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #e3f2fd;
            text-align: right;
        }
        .bot-message {
            background-color: #f5f5f5;
        }
        .input-container {
            display: flex;
            gap: 10px;
        }
        #userInput {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-messages" id="chatMessages"></div>
    <div class="input-container">
        <input type="text" id="userInput" placeholder="请输入消息...">
        <button onclick="sendMessage()">发送</button>
    </div>
</div>

<script>

    function sendMessage() {
        const userInput = document.getElementById('userInput');
        const message = userInput.value.trim();
        if (!message) return;

        addMessage(message, 'user');
        userInput.value = '';

        // 创建唯一ID的占位消息用于增量更新
        const placeholderId = `bot-${Date.now()}`;
        addMessage('', 'bot', placeholderId); // 初始为空内容

        fetch('http://127.0.0.1:26061/dify/stream/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                query: message,
                userId: 123,
                conversationId: null
            })
        })
            .then(response => {
                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let buffer = '';
                let partialChunk = '';

                const processData = (dataStr) => {
                    const lines = (partialChunk + dataStr).split('\n');
                    partialChunk = lines.pop() || ''; // 保存未完成的行

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6)); // 提取JSON数据
                                const answerChunk = data.answer;
                                // 关键修改:追加内容而非覆盖
                                const el = document.getElementById(placeholderId);
                                if (el) {
                                    el.textContent += answerChunk; // 使用 += 实现增量
                                    el.scrollIntoView({ behavior: 'smooth' });
                                }
                            } catch (e) {
                                console.error('解析错误:', e);
                            }
                        }
                    }
                };

                const readStream = () => {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            // 流结束后的清理工作
                            if (partialChunk) processData('');
                            return;
                        }
                        buffer += decoder.decode(value, { stream: true });
                        processData(buffer);
                        buffer = '';
                        readStream();
                    });
                };

                readStream();
            })
            .catch(err => {
                console.error('请求失败:', err);
                addMessage('请求出错,请稍后重试', 'bot');
            });
    }

    // 辅助函数:添加消息到聊天窗口
    function addMessage(text, sender, messageId) {
        const chatMessages = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.id = messageId || '';
        messageDiv.className = `message ${sender}-message`;
        messageDiv.textContent = text;
        chatMessages.appendChild(messageDiv);
        messageDiv.scrollIntoView({ behavior: 'smooth' });
    }


</script>
</body>
</html>