File size: 8,174 Bytes
70eb3ca 5398f51 | 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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | <!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Qwen Turbo AI</title>
<!-- Подключаем библиотеку для Markdown (жирный текст, код) -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
:root {
--bg-color: #212121;
--chat-bg: #2f2f2f;
--user-msg-bg: #303030; /* Темный */
--ai-msg-bg: #212121;
--accent: #10a37f;
--text: #ececec;
}
body { margin: 0; font-family: 'Segoe UI', Roboto, sans-serif; background: var(--bg-color); color: var(--text); display: flex; flex-direction: column; height: 100vh; }
/* Заголовок */
header { padding: 15px; background: #171717; border-bottom: 1px solid #333; display: flex; align-items: center; justify-content: space-between; }
h1 { margin: 0; font-size: 1.2rem; }
/* Чат */
#chat-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 20px; scroll-behavior: smooth; }
.message { display: flex; gap: 15px; max-width: 800px; margin: 0 auto; width: 100%; }
.avatar { width: 30px; height: 30px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 0.9rem; flex-shrink: 0; }
.user-avatar { background: #555; }
.ai-avatar { background: var(--accent); }
.content { line-height: 1.6; font-size: 1rem; padding-top: 4px; overflow-wrap: break-word; width: 100%; }
.content p { margin-top: 0; }
.content pre { background: #000; padding: 10px; border-radius: 5px; overflow-x: auto; }
/* Поле ввода */
#input-area { background: #171717; padding: 20px; border-top: 1px solid #333; }
.input-wrapper { max-width: 800px; margin: 0 auto; position: relative; }
textarea { width: 100%; background: #40414f; border: 1px solid #555; color: white; padding: 12px 45px 12px 15px; border-radius: 10px; resize: none; outline: none; height: 50px; font-family: inherit; font-size: 1rem; box-sizing: border-box; }
textarea:focus { border-color: var(--accent); }
button#send-btn { position: absolute; right: 10px; bottom: 10px; background: transparent; border: none; cursor: pointer; color: #ccc; }
button#send-btn:hover { color: white; }
/* Настройки (поиск) */
.controls { max-width: 800px; margin: 0 auto 10px; display: flex; gap: 15px; font-size: 0.9rem; color: #aaa; }
.checkbox-wrapper { display: flex; align-items: center; gap: 5px; cursor: pointer; }
.checkbox-wrapper input { cursor: pointer; accent-color: var(--accent); }
/* Анимация курсора */
.typing::after { content: '▋'; animation: blink 1s infinite; margin-left: 2px; }
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
</style>
</head>
<body>
<header>
<h1>🤖 Qwen Turbo AI</h1>
<div style="font-size: 0.8rem; color: #777;">Powered by HuggingFace</div>
</header>
<div id="chat-container">
<!-- Приветственное сообщение -->
<div class="message">
<div class="avatar ai-avatar">AI</div>
<div class="content">Привет! Я быстрый ИИ на базе Qwen 2.5. Могу искать информацию в интернете. Чем помочь?</div>
</div>
</div>
<div id="input-area">
<div class="controls">
<label class="checkbox-wrapper">
<input type="checkbox" id="web-search"> 🌐 Поиск в интернете (Tavily)
</label>
</div>
<div class="input-wrapper">
<textarea id="user-input" placeholder="Введите сообщение..." onkeydown="handleKey(event)"></textarea>
<button id="send-btn" onclick="sendMessage()">➤</button>
</div>
</div>
<script>
const chatContainer = document.getElementById('chat-container');
const userInput = document.getElementById('user-input');
const webSearch = document.getElementById('web-search');
let history = []; // Храним историю диалога
function handleKey(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
}
async function sendMessage() {
const text = userInput.value.trim();
if (!text) return;
// 1. Добавляем сообщение пользователя
appendMessage('user', text);
userInput.value = '';
// 2. Создаем пустой блок для ответа ИИ
const aiContentDiv = appendMessage('ai', '');
aiContentDiv.classList.add('typing'); // Курсор мигает
// Формируем историю для отправки
const messagesToSend = [...history, { role: "user", content: text }];
try {
// 3. Отправляем запрос
const response = await fetch('/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: messagesToSend,
stream: true,
use_search: webSearch.checked
})
});
// 4. Читаем поток (Streaming)
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullText = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const jsonStr = line.slice(6);
if (jsonStr === '[DONE]') break;
try {
const json = JSON.parse(jsonStr);
const delta = json.choices[0].delta.content;
if (delta) {
fullText += delta;
// Рендерим Markdown на лету
aiContentDiv.innerHTML = marked.parse(fullText);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
} catch (e) { }
}
}
}
// Сохраняем в историю (без контекста поиска, чтобы экономить токены, или с ним)
history.push({ role: "user", content: text });
history.push({ role: "assistant", content: fullText });
aiContentDiv.classList.remove('typing'); // Убираем курсор
} catch (error) {
aiContentDiv.innerHTML = `<span style="color:red">Ошибка: ${error.message}</span>`;
}
}
function appendMessage(role, text) {
const msgDiv = document.createElement('div');
msgDiv.className = 'message';
const avatar = document.createElement('div');
avatar.className = `avatar ${role === 'user' ? 'user-avatar' : 'ai-avatar'}`;
avatar.textContent = role === 'user' ? 'Вы' : 'AI';
const content = document.createElement('div');
content.className = 'content';
content.innerHTML = role === 'user' ? text : ''; // AI текст заполним позже
msgDiv.appendChild(avatar);
msgDiv.appendChild(content);
chatContainer.appendChild(msgDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
return content;
}
</script>
</body>
</html> |