注意:你可以点击右下角设置

选择合适的背景和字体方便阅读。

与deepseek对话

<style>
    body {
        font-family: Arial, sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
    }

    #chat-container {
        background-color: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 20px;
    }

    #chat-history {
        height: 400px;
        overflow-y: auto;
        margin-bottom: 20px;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .message {
        margin: 5px 0;
        padding: 12px 15px;
        border-radius: 15px;
        max-width: 85%;
        word-wrap: break-word;
        animation: fadeIn 0.3s ease-in;
    }

    .user-message {
        background-color: #e3f2fd;
        margin-left: auto;
        border-bottom-right-radius: 5px;
    }

    .ai-message {
        background-color: #f0f0f0;
        border-bottom-left-radius: 5px;
    }

    #input-container {
        display: flex;
        gap: 10px;
        position: relative;
    }

    #user-input {
        flex: 1;
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 25px;
        outline: none;
        transition: border-color 0.3s;
    }

    #user-input:focus {
        border-color: #007bff;
    }

    button {
        padding: 12px 25px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 25px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    button:hover {
        background-color: #0056b3;
    }

    .loading {
        color: #666;
        font-style: italic;
        position: relative;
        padding-left: 25px;
    }

    .loading::after {
        content: '...';
        position: absolute;
        animation: dots 1.5s infinite;
    }
.reasoning-content {
        color: #666;
        font-size: 0.9em;
        margin-top: 5px;
        padding: 8px;
        background-color: #f8f9fa;
        border-radius: 8px;
        border-left: 3px solid #007bff;
    }

.reasoning-container {
background-color: #fff3e0;
border: 1px solid #ffcc80;
border-radius: 8px;
margin: 10px 0;
padding: 12px;
}

    .reasoning-header {
        color: #ef6c00;
        font-size: 0.9em;
        font-weight: bold;
        margin-bottom: 8px;
    }

    .reasoning-content {
        color: #bf360c;
        font-size: 0.85em;
        line-height: 1.4;
        white-space: pre-wrap;
    }

    .streaming-answer {
        border-left: 3px solid #007bff;
        padding-left: 10px;
        margin: 5px 0;
    }

/* 新增上下文按钮样式 */
#context-toggle {
background-color: #28a745;
padding: 12px 15px;
transition: all 0.3s;
}

#context-toggle:hover {
opacity: 0.9;
}

/* 禁用状态样式 */
#context-toggle[disabled] {
background-color: #6c757d;
cursor: not-allowed;
}

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    @keyframes dots {
        0%, 20% { content: '.'; }
        40% { content: '..'; }
        60%, 100% { content: '...'; }
    }
</style>
    </div>
</div>

<script>

let chatHistory = [];
let isContextEnabled = true;
// 注意:实际部署时应将API密钥放在后端处理
const API_KEY = ‘Bearer sk-zgvablorrcxisbjvwdrxovvjiitbuccfxcwsswlnauszxiwk’;
const API_URL = ‘https://api.siliconflow.cn/v1/chat/completions’;
async function sendMessage() {
const userInput = document.getElementById(‘user-input’);
const message = userInput.value.trim();
if (!message) return;

// 添加用户消息到历史记录
const userMessage = { role: "user", content: message };
chatHistory.push(userMessage);

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

try {
    // 创建思考容器和回答容器
    const reasoningId = addReasoningContainer();
    const answerId = addMessage('ai', '');
    
    // 根据上下文状态构建请求消息
    const requestMessages = isContextEnabled 
        ? [...chatHistory] 
        : [userMessage]; // 不关联上下文时只发送当前消息

    const response = await fetch(API_URL, {
        method: 'POST',
        headers: {
            'Authorization': API_KEY,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            model: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
            stream: true,
            max_tokens: 4096,
            temperature: 0.7,
            messages: requestMessages
        })
    });

            if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            let answerContent = '';
            let reasoningContent = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });
                
                // 改进流式数据处理
                const parts = buffer.split('\n\n');
                buffer = parts.pop() || '';

                for (const part of parts) {
                    const lines = part.split('\n').filter(line => line.startsWith('data: '));
                    
                    for (const line of lines) {
                        try {
                            const data = JSON.parse(line.slice(6));
                            const delta = data.choices[0].delta;
			 if (delta.reasoning_content !== undefined) {
    reasoningContent += delta.reasoning_content || '';
    updateReasoning(reasoningId, reasoningContent);
}
                            
                            // 模拟思考过程(实际应根据API响应调整)
                            if (delta.content) {
                                // 当检测到特定关键词时添加思考内容
                                if (delta.content.includes('?')) {
                                    reasoningContent += `分析问题: ${delta.content}\n`;
                                    updateReasoning(reasoningId, reasoningContent);
                                }
                                
                                answerContent += delta.content;
                                updateAnswer(answerId, answerContent);
                            }
                        } catch (e) {
                            console.error('解析错误:', e);
                        }
                    }
                }
            }

            // 完成处理后移除加载状态
            finalizeProcessing(reasoningId, answerId, answerContent);

        } catch (error) {
            console.error('错误:', error);
            updateMessage(answerId, `请求失败: ${error.message}`);
            document.getElementById(reasoningId)?.remove();
        }
    }

    function addReasoningContainer() {
        const chatHistory = document.getElementById('chat-history');
        const container = document.createElement('div');
        const id = `reasoning-${Date.now()}`;
        
        container.id = id;
        container.className = 'reasoning-container';
        container.innerHTML = `
            <div class="reasoning-header">思考过程</div>
            <div class="reasoning-content loading"></div>
        `;
        
        chatHistory.appendChild(container);
        return id;
    }

    function updateReasoning(id, content) {
        const container = document.getElementById(id);
        if (container) {
            const contentDiv = container.querySelector('.reasoning-content');
            contentDiv.innerHTML = content + '<span class="loading-dots"></span>';
            container.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }

    function updateAnswer(id, content) {
        const container = document.getElementById(id);

        if (container) {
            container.innerHTML = `<div class="streaming-answer">${content}</div>`;
            container.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }

    function finalizeProcessing(reasoningId, answerId, answerContent) {
        // 清理思考容器的加载状态
        const reasoningContainer = document.getElementById(reasoningId);
        if (reasoningContainer) {
            const contentDiv = reasoningContainer.querySelector('.reasoning-content');
            contentDiv.classList.remove('loading');
        }

        // 确保最终答案格式
        const answerContainer = document.getElementById(answerId);
        if (answerContainer) {
            answerContainer.innerHTML = answerContent;
        }
    }

function addMessage(role, content, isLoading = false) {
const chatHistoryDiv = document.getElementById(‘chat-history’);
const messageDiv = document.createElement(‘div’);
const messageId = msg-${Date.now()};

messageDiv.id = messageId;
messageDiv.className = `message ${role}-message${isLoading ? ' loading' : ''}`;

// 添加上下文序号
const contextNumber = document.createElement('small');
contextNumber.style.display = 'block';
contextNumber.style.marginBottom = '5px';
contextNumber.style.opacity = '0.6';
contextNumber.textContent = `对话${chatHistory.length + 1}`;

messageDiv.appendChild(contextNumber);
messageDiv.innerHTML += content;

chatHistoryDiv.appendChild(messageDiv);
chatHistoryDiv.scrollTop = chatHistoryDiv.scrollHeight;
return messageId;

}
function toggleContext() {
const contextBtn = document.getElementById(‘context-toggle’);
isContextEnabled = !isContextEnabled;

if (isContextEnabled) {
    contextBtn.textContent = '关闭上下文';
    contextBtn.style.backgroundColor = '#28a745';
} else {
    contextBtn.textContent = '启用上下文';
    contextBtn.style.backgroundColor = '#6c757d';
    chatHistory = []; // 清空历史记录
}

}

    function updateMessage(id, newContent) {
        const messageDiv = document.getElementById(id);
        if (messageDiv) {
            messageDiv.textContent = newContent;
            messageDiv.classList.remove('loading');
            messageDiv.scrollIntoView({ behavior: 'smooth' });
        }
    }

function clearContext() {
chatHistory = [];
isContextEnabled = false;

// 清空聊天显示
const historyContainer = document.getElementById('chat-history');
historyContainer.innerHTML = '';

// 更新按钮状态
const contextBtn = document.getElementById('context-toggle');
contextBtn.textContent = '启用上下文';
contextBtn.style.backgroundColor = '#6c757d';

}

    // 回车发送功能
    document.getElementById('user-input').addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });