Spaces:
Running

chatdepp / embed.html
ericmendez's picture
Como configurar com a minha API? - Initial Deployment
ca7e0e3 verified
Raw History Blame Contribute Delete
14.2 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DeepSeek Chat Embed</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://unpkg.com/feather-icons"></script>
<style>
.chat-container {
height: calc(100vh - 64px);
}
.message-stream {
height: calc(100% - 72px);
}
.markdown-content pre {
background-color: #1e293b;
color: #f8fafc;
padding: 1rem;
border-radius: 0.5rem;
overflow-x: auto;
}
.markdown-content code {
background-color: #1e293b;
color: #f8fafc;
padding: 0.2rem 0.4rem;
border-radius: 0.25rem;
font-family: monospace;
}
</style>
</head>
<body class="bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
<div id="app" class="flex flex-col h-screen">
<!-- Header (optional, can be hidden) -->
<header id="chat-header" class="bg-white dark:bg-gray-800 shadow-sm">
<div class="px-4 py-3 flex justify-between items-center">
<div class="flex items-center space-x-2">
<div class="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center">
<i data-feather="message-square" class="text-white"></i>
</div>
<h1 class="text-lg font-bold">DeepSeek Chat</h1>
</div>
<button id="close-embed" class="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700">
<i data-feather="x"></i>
</button>
</div>
</header>
<!-- Chat Area -->
<main class="flex-1 flex flex-col">
<div id="chat-container" class="chat-container flex-1 flex flex-col">
<!-- Messages -->
<div id="message-stream" class="message-stream overflow-y-auto p-4 space-y-6">
<!-- Messages will be loaded here -->
<div class="text-center py-12 text-gray-500 dark:text-gray-400">
<div class="mx-auto w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4">
<i data-feather="message-square" class="w-8 h-8"></i>
</div>
<h3 class="text-lg font-medium">Start a new conversation</h3>
<p class="mt-1">Ask anything or try one of the example prompts</p>
</div>
</div>
<!-- Input Area -->
<div class="p-4 border-t border-gray-200 dark:border-gray-700">
<form id="message-form" class="relative">
<textarea id="message-input" rows="1" placeholder="Type your message..."
class="w-full px-4 py-3 pr-12 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"></textarea>
<button type="submit" id="send-btn" class="absolute right-3 bottom-3 p-1 rounded-md text-blue-500 hover:bg-blue-50 dark:hover:bg-gray-700">
<i data-feather="send"></i>
</button>
<button type="button" id="stop-btn" class="absolute right-3 bottom-3 p-1 rounded-md text-red-500 hover:bg-red-50 dark:hover:bg-gray-700 hidden">
<i data-feather="square"></i>
</button>
</form>
</div>
</div>
</main>
</div>
<script>
// Initialize Feather Icons
feather.replace();
// Get URL parameters
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
const theme = urlParams.get('theme') || 'auto';
const lang = urlParams.get('lang') || 'en';
const hideHeader = urlParams.get('hideHeader') === '1';
const templateId = urlParams.get('templateId');
const prompt = urlParams.get('prompt');
// Apply theme
if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark');
}
// Hide header if requested
if (hideHeader) {
document.getElementById('chat-header').classList.add('hidden');
}
// DOM Elements
const messageForm = document.getElementById('message-form');
const messageInput = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
const stopBtn = document.getElementById('stop-btn');
const messageStream = document.getElementById('message-stream');
const closeEmbed = document.getElementById('close-embed');
// Event Listeners
messageForm.addEventListener('submit', async (e) => {
e.preventDefault();
const message = messageInput.value.trim();
if (!message) return;
// Add user message to chat
addMessage('user', message);
messageInput.value = '';
// Show stop button, hide send button
sendBtn.classList.add('hidden');
stopBtn.classList.remove('hidden');
// Create assistant message placeholder
const assistantMessageId = 'msg-' + Date.now();
addMessage('assistant', '', assistantMessageId);
// Scroll to bottom
messageStream.scrollTop = messageStream.scrollHeight;
try {
// Call API with token
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [
{role: 'system', content: prompt || 'You are a helpful AI assistant.'},
{role: 'user', content: message}
],
temperature: 0.7,
max_tokens: 1024,
stream: true
})
});
if (!response.ok) {
throw new Error('API request failed');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let assistantMessage = '';
while (true) {
const {done, value} = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.substring(6);
if (data === '[DONE]') break;
try {
const parsed = JSON.parse(data);
if (parsed.choices && parsed.choices[0].delta.content) {
assistantMessage += parsed.choices[0].delta.content;
updateMessage(assistantMessageId, assistantMessage);
messageStream.scrollTop = messageStream.scrollHeight;
// Notify parent of height change
window.parent.postMessage({
type: 'heightChange',
height: document.body.scrollHeight
}, '*');
}
} catch (e) {
console.error('Error parsing JSON:', e);
}
}
}
}
// Notify parent of message received
window.parent.postMessage({
type: 'messageReceived',
content: assistantMessage
}, '*');
} catch (error) {
console.error('Error:', error);
updateMessage(assistantMessageId, 'Sorry, there was an error processing your request.');
// Notify parent of error
window.parent.postMessage({
type: 'error',
message: error.message
}, '*');
} finally {
sendBtn.classList.remove('hidden');
stopBtn.classList.add('hidden');
messageStream.scrollTop = messageStream.scrollHeight;
// Notify parent of height change
window.parent.postMessage({
type: 'heightChange',
height: document.body.scrollHeight
}, '*');
}
});
stopBtn.addEventListener('click', () => {
// TODO: Implement abort controller for streaming
sendBtn.classList.remove('hidden');
stopBtn.classList.add('hidden');
});
closeEmbed.addEventListener('click', () => {
window.parent.postMessage({
type: 'closeChat'
}, '*');
});
// Listen for messages from parent
window.addEventListener('message', (event) => {
if (event.data.type === 'setTheme') {
if (event.data.theme === 'dark') {
document.documentElement.classList.add('dark');
} else if (event.data.theme === 'light') {
document.documentElement.classList.remove('dark');
}
} else if (event.data.type === 'setLang') {
// TODO: Implement language change
} else if (event.data.type === 'setTemplate') {
// TODO: Implement template change
} else if (event.data.type === 'focus') {
messageInput.focus();
} else if (event.data.type === 'resize') {
// TODO: Handle resize if needed
}
});
// Notify parent that embed is ready
window.parent.postMessage({
type: 'ready'
}, '*');
// Initial height notification
window.parent.postMessage({
type: 'heightChange',
height: document.body.scrollHeight
}, '*');
// Helper functions
function addMessage(role, content, id = '') {
if (role === 'user') {
const messageDiv = document.createElement('div');
messageDiv.className = 'flex justify-end';
messageDiv.innerHTML = `
<div class="max-w-3xl bg-blue-500 text-white rounded-lg p-4">
<div class="markdown-content">${escapeHtml(content)}</div>
</div>
`;
messageStream.appendChild(messageDiv);
} else if (role === 'assistant') {
const messageDiv = document.createElement('div');
messageDiv.className = 'flex justify-start';
messageDiv.id = id;
messageDiv.innerHTML = `
<div class="max-w-3xl bg-gray-100 dark:bg-gray-700 rounded-lg p-4">
<div class="markdown-content">${escapeHtml(content)}</div>
</div>
`;
messageStream.appendChild(messageDiv);
}
feather.replace();
// Notify parent of message sent
if (role === 'user') {
window.parent.postMessage({
type: 'messageSent',
content: content
}, '*');
}
}
function updateMessage(id, content) {
const messageDiv = document.getElementById(id);
if (messageDiv) {
const contentDiv = messageDiv.querySelector('.markdown-content');
if (contentDiv) {
contentDiv.innerHTML = markdownToHtml(content);
}
}
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function markdownToHtml(markdown) {
// Simple markdown to HTML conversion (basic support for **bold** and `code`)
let html = escapeHtml(markdown);
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
html = html.replace(/`(.*?)`/g, '<code>$1</code>');
html = html.replace(/\n/g, '<br>');
return html;
}
// Auto-resize textarea
messageInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
// Notify parent of height change
window.parent.postMessage({
type: 'heightChange',
height: document.body.scrollHeight
}, '*');
});
</script>
</body>
</html>