specialized-agents / static /multi-agent.html
pvanand's picture
Update static/multi-agent.html
8c4efa5 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Multi Agent</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script>
<style>
:root {
--primary-color: #304b76;
--secondary-color: #f0f8ff;
--text-color: #333;
--background-color: #f5f7fa;
}
body {
font-family: 'Poppins', sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
background-color: var(--background-color);
color: var(--text-color);
font-size: 16px;
}
#app {
max-width: 900px;
margin: 0 auto;
padding: 10px;
}
.chat-container {
background-color: #ffffff;
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
overflow: hidden;
display: flex;
flex-direction: column;
height: 98vh;
transition: all 0.3s ease;
}
.messages {
flex-grow: 1;
overflow-y: auto;
padding: 20px;
display: flex;
flex-direction: column;
}
.message {
max-width: 80%;
margin-bottom: 20px;
padding: 10px 20px;
border-radius: 20px;
font-size: 1em;
line-height: 1.5;
word-wrap: break-word;
animation: fadeIn 0.5s ease;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.user-message {
background-color: var(--primary-color);
color: #ffffff;
align-self: flex-end;
border-bottom-right-radius: 5px;
}
.bot-message {
background-color: var(--secondary-color);
color: var(--text-color);
align-self: flex-start;
border-bottom-left-radius: 5px;
position: relative;
}
.copy-button {
position: absolute;
top: 5px;
right: 5px;
background-color: transparent;
border: none;
cursor: pointer;
padding: 5px;
transition: all 0.3s ease;
}
.copy-button svg {
width: 16px;
height: 16px;
stroke: var(--primary-color);
}
.copy-button:hover {
transform: scale(1.1);
}
.input-area {
display: flex;
padding: 15px;
background-color: #ffffff;
border-top: 1px solid #e0e0e0;
}
#user-input {
flex-grow: 1;
padding: 12px 15px;
border: 2px solid var(--primary-color);
border-radius: 15px;
font-size: 1em;
outline: none;
transition: all 0.3s ease;
}
#user-input:focus {
box-shadow: 0 0 0 3px rgba(0,119,190,0.3);
}
.send-button, .reset-button {
background-color: var(--primary-color);
color: #ffffff;
border: none;
border-radius: 50%;
width: 50px;
height: 50px;
margin-left: 10px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.send-button:hover, .reset-button:hover {
background-color: #005fa3;
transform: scale(1.05);
}
.send-button svg, .reset-button svg {
width: 24px;
height: 24px;
}
.option-buttons {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 15px;
}
.option-button {
background-color: #ffffff;
border: 2px solid var(--primary-color);
border-radius: 20px;
padding: 8px 16px;
font-size: 0.875em;
cursor: pointer;
transition: all 0.3s ease;
}
.option-button:hover {
background-color: var(--secondary-color);
transform: translateY(-2px);
}
.option-button.selected {
background-color: var(--primary-color);
color: #ffffff;
}
.audio-button {
background: none;
border: none;
cursor: pointer;
padding: 0;
margin-top: 10px;
transition: all 0.3s ease;
}
.audio-button:hover {
transform: scale(1.1);
}
.audio-button svg {
width: 30px;
height: 30px;
fill: var(--primary-color);
}
.dot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #5853c0;
margin: 0 3px;
animation: bounce 1.4s infinite ease-in-out;
}
.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce {
0%, 80%, 100% {
transform: scale(0);
} 40% {
transform: scale(1.0);
}
}
.chat-container {
position: relative;
}
.input-area {
position: absolute;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
transition: transform 0.3s ease;
}
.messages {
padding-bottom: 80px;
}
.input-hidden {
transform: translateY(100%);
}
.tool-options {
position: absolute;
bottom: 100%;
left: 0;
background-color: #ffffff;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
width: auto;
min-width: 120px;
margin-bottom: 10px;
}
.tool-options button {
padding: 10px 15px;
border: none;
background: none;
text-align: left;
cursor: pointer;
white-space: nowrap;
transition: background-color 0.3s ease;
font-size: 1em;
font-weight: 500;
color: #333;
border-radius: 4px;
}
.tool-options button:hover {
background-color: #e0e0e0;
color: #000;
}
details {
margin-top: 10px;
border-radius: 4px;
padding: 5px;
}
summary {
cursor: pointer;
font-weight: bold;
}
.ref-content {
margin-top: 10px;
justify-content: center;
}
.ref-item {
margin-bottom: 0px;
}
.ref-item small {
color: #666;
}
hr {
margin: 10px 0;
border: none;
border-top: 1px solid #eee;
}
.ref-link {
text-decoration: none;
color: inherit;
display: block;
padding: 5px;
border-radius: 4px;
transition: background-color 0.2s;
}
.ref-link:hover {
background-color: #e3e3ea;
color: inherit;
}
.ref-link:visited {
color: inherit;
}
img, video {
max-width: 100%;
height: auto;
}
.download-buttons {
display: flex;
gap: 5px;
margin-top: 5px;
}
.download-button {
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 3px;
padding: 2px 5px;
font-size: 0.8em;
cursor: pointer;
transition: background-color 0.3s;
}
.download-button:hover {
background-color: #e0e0e0;
}
@media (max-width: 600px) {
body {
font-size: 14px;
}
#app {
padding: 5px;
}
.chat-container {
height: 100vh;
border-radius: 0;
}
.messages {
padding: 10px;
}
.message {
max-width: 90%;
}
#user-input {
font-size: 16px;
padding: 12px;
}
.send-button, .reset-button {
width: 44px;
height: 44px;
}
.tool-options {
width: 100%;
left: 0;
right: 0;
}
.tool-options button {
padding: 12px 15px;
}
}
@media (max-width: 900px) and (orientation: landscape) {
.chat-container {
height: 100vh;
}
.messages {
max-height: calc(100vh - 60px);
}
}
@media (hover: none) {
.option-button:active {
background-color: var(--primary-color);
color: #ffffff;
}
}
</style>
</head>
<body>
<div id="app">
<div class="chat-container">
<div class="messages" ref="messageContainer" @scroll="handleScroll">
<div v-for="(message, index) in messages" :key="index"
:class="['message', message.type === 'user' ? 'user-message' : 'bot-message']">
<div v-if="message.type === 'bot' && message.content === ''" id="typing-animation"></div>
<div v-else v-html="message.content"></div>
<button v-if="message.type === 'bot' && message.audio" @click="toggleAudio(index)" class="audio-button">
<svg v-if="!message.isPlaying" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
</svg>
</button>
<button v-if="message.type === 'bot' && message.rawResponse" @click="copyMarkdownToClipboard(message.rawResponse)" class="copy-button">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path>
<rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect>
</svg>
</button>
<div v-if="message.type === 'bot' && message.rawResponse" class="option-buttons">
<div style="display: flex; align-items: center; gap: 10px;">
<span>Would you like to download this chat as</span>
<button @click="downloadResponse(message.rawResponse, 'pdf')" class="option-button">PDF</button>
<button @click="downloadResponse(message.rawResponse, 'docx')" class="option-button">DOCX</button>
</div>
</div>
</div>
</div>
<div class="input-area" :class="{ 'input-hidden': isScrollingUp }">
<input type="text" id="user-input" v-model="userInput" @keyup.enter="sendMessage" @input="handleInput($event)" placeholder="Type your message... (type / to see available tools)">
<div v-if="showToolOptions" class="tool-options">
<button @click="selectTool('web')">/web</button>
<button @click="selectTool('news')">/news</button>
</div>
<button class="send-button" @click="sendMessage">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="22" y1="2" x2="11" y2="13"></line>
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
</svg>
</button>
<button class="reset-button" @click="resetConversation">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path>
<path d="M3 3v5h5"></path>
</svg>
</button>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
marked.setOptions({
highlight: function (code, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(code, { language: lang }).value;
} else {
return hljs.highlightAuto(code).value;
}
},
sanitize: false
});
function createTypingAnimation() {
const container = document.getElementById('typing-animation');
for (let i = 0; i < 3; i++) {
const dot = document.createElement('div');
dot.className = 'dot';
container.appendChild(dot);
}
}
function extractCustomFileName(html) {
// Try to find the first h1-h4 tag content
const headingMatch = html.match(/<h[1-4][^>]*>(.*?)<\/h[1-4]>/i);
if (headingMatch) {
return headingMatch[1].trim();
}
// If no heading found, use the first 7 words
const textContent = html.replace(/<[^>]+>/g, ' ').trim();
const words = textContent.split(/\s+/);
return words.slice(0, 7).join(' ');
}
async function convertHtmlToFile(html, fileType, customFileName = '') {
const url = 'https://pvanand-web-scraping.hf.space/html_to_' + fileType;
customFileName = extractCustomFileName(html);
function sanitizeFileName(name) {
return (name.replace(/[^a-z0-9\s]/gi, '')
.toLowerCase()
.replace(/\s+/g, '_')
.substring(0, 50)) || 'generated_report';
}
const fileName = `${sanitizeFileName(customFileName || 'generated_report')}.${fileType}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ html_content: html })
});
if (!response.ok) throw new Error('Conversion failed');
const blob = await response.blob();
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(a.href);
} catch (error) {
throw new Error(`Failed to download ${fileName}. Please try again.`);
}
}
const app = new Vue({
el: '#app',
data: {
messages: [],
userInput: '',
selectedOptions: {},
conversationId: '',
currentAudio: null,
isScrollingUp: false,
lastScrollTop: 0,
tool_call: 'auto',
showToolOptions: false,
},
methods: {
async sendMessage() {
if (!this.userInput.trim()) return;
this.messages.push({ type: 'user', content: marked.parse(this.userInput) });
const message = this.userInput;
this.userInput = '';
this.selectedOptions = {};
let streamingIndex = this.messages.push({ type: 'bot', content: '' }) - 1;
this.$nextTick(() => {
createTypingAnimation();
});
try {
const response = await fetch('https://pvanand-general-chat.hf.space/v2/followup-tools-agent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': '44d5c2ac18ced6fc25c1e57dcd06fc0b31fb4ad97bf56e67540671a647465df4'
},
body: JSON.stringify({
query: message,
model_id: 'openai/gpt-4o-mini',
conversation_id: this.conversationId,
user_id: 'string',
tool_call: this.tool_call,
})
});
const reader = response.body.getReader();
let rawResponse = '';
let jsonData = null;
let refData = null; // New variable to hold reference data
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = new TextDecoder().decode(value);
if (chunk.includes('<json>')) {
const [textPart, jsonPart] = chunk.split('<json>');
rawResponse += textPart;
const jsonString = jsonPart.split('</json>')[0];
// Check for <ref> tag first
const refMatch = jsonString.match(/<ref>(.*?)<\/ref>/);
if (refMatch) {
refData = JSON.parse(refMatch[1]); // Parse the reference data
} else {
try {
jsonData = JSON.parse(jsonString); // Parse JSON only if <ref> is not present
} catch (error) {
console.error("JSON parsing error:", error);
console.log("Raw JSON string:", jsonString);
}
}
} else {
rawResponse += chunk;
}
// After processing, display the refData if it exists
if (refData) {
const refMessage = `
<details>
<summary>Reference Information</summary>
<div class="ref-content">
${refData.map(item => `
<div class="ref-item">
<a href="${item.url}" target="_blank" class="ref-link">
<strong>${item.title}</strong>: ${item.snippet}
</a>
<br>
<small>Last updated: ${item.last_updated}</small>
</div>
`).join('<hr>')}
</div>
</details>
`;
this.messages.push({ type: 'bot', content: refMessage });
}
rawResponse = rawResponse.replace(/<\/?response>/g, '');
rawResponse = rawResponse.replace(/<tools>[\s\S]*?<\/tools>/g, '');
rawResponse = rawResponse.replace(/<interact>[\s\S]*?<\/interact>/g, '');
rawResponse = rawResponse.replace(/<tool>[\s\S]*?<\/tool>/g, '');
this.$set(this.messages[streamingIndex], 'content', marked.parse(rawResponse));
this.$set(this.messages[streamingIndex], 'rawResponse', rawResponse);
}
if (jsonData) {
if (jsonData.tools && jsonData.tools.length > 0) {
let toolsMessage = "\n\n**Tools Used:**\n";
jsonData.tools.forEach(tool => {
toolsMessage += `- ${tool.name.charAt(0).toUpperCase() + tool.name.slice(1)}: ${tool.input}\n`;
});
this.$set(this.messages[streamingIndex], 'content', this.messages[streamingIndex].content + marked.parse(toolsMessage));
}
if (jsonData.clarification && jsonData.clarification.length > 0) {
streamingIndex = this.messages.push({ type: 'bot', content: '' }) - 1;
this.renderClarificationQuestions(jsonData.clarification, streamingIndex);
}
}
rawResponse = rawResponse.replace(/[#!*_\[\]\(\)`]/g, '');
const audioUrl = await this.convertToSpeech(rawResponse);
if (audioUrl) {
this.$set(this.messages[streamingIndex], 'audio', audioUrl);
}
} catch (error) {
console.error('Error:', error);
this.messages.push({ type: 'bot', content: 'An error occurred while processing your request.' });
}
this.$nextTick(() => this.scrollToBottom());
},
handleScroll(event) {
const st = event.target.scrollTop;
this.isScrollingUp = st < this.lastScrollTop;
this.lastScrollTop = st <= 0 ? 0 : st;
},
renderClarificationQuestions(clarification, messageIndex) {
if (!clarification || clarification.length === 0) return;
let clarificationHtml = '';
clarification.forEach((item, questionIndex) => {
clarificationHtml += `<strong>${item.question}</strong><br>`;
clarificationHtml += '<div class="option-buttons">';
item.options.forEach((option, optionIndex) => {
const escapedOption = option.replace(/'/g, "\\'");
clarificationHtml += `<button class="option-button" onclick="app.toggleOption('${escapedOption}', ${questionIndex}, ${optionIndex})">${option}</button>`;
});
clarificationHtml += '</div><br>';
});
this.$set(this.messages[messageIndex], 'content', this.messages[messageIndex].content + marked.parse(clarificationHtml));
this.$nextTick(() => {
this.scrollToBottom();
this.updateButtonStates();
});
},
toggleOption(option, questionIndex, optionIndex) {
if (!this.selectedOptions[questionIndex]) {
this.$set(this.selectedOptions, questionIndex, []);
}
const index = this.selectedOptions[questionIndex].indexOf(option);
if (index > -1) {
this.selectedOptions[questionIndex].splice(index, 1);
} else {
this.selectedOptions[questionIndex].push(option);
}
this.updateInputFromSelectedOptions();
this.updateButtonStates();
},
updateInputFromSelectedOptions() {
this.userInput = Object.entries(this.selectedOptions)
.map(([questionIndex, options]) =>
`Q${parseInt(questionIndex) + 1}: ${options.join(', ')}`)
.join(' | ');
this.$nextTick(() => document.getElementById('user-input').focus());
},
updateButtonStates() {
Object.entries(this.selectedOptions).forEach(([questionIndex, options]) => {
const buttons = document.querySelectorAll(`.option-buttons:nth-of-type(${parseInt(questionIndex) + 1}) .option-button`);
buttons.forEach((button) => {
if (options.includes(button.textContent)) {
button.classList.add('selected');
} else {
button.classList.remove('selected');
}
});
});
},
resetConversation() {
this.conversationId = uuid.v4();
this.messages = [];
this.selectedOptions = {};
this.userInput = '';
this.isScrollingUp = false;
this.lastScrollTop = 0;
this.tool_call = 'auto';
this.showToolOptions = false;
this.$nextTick(() => {
if (this.$refs.messageContainer) {
this.$refs.messageContainer.scrollTop = 0;
}
});
const inputArea = document.querySelector('.input-area');
if (inputArea) inputArea.classList.remove('input-hidden');
},
scrollToBottom() {
const container = this.$refs.messageContainer;
container.scrollTop = container.scrollHeight;
},
async convertToSpeech(text) {
const voice = 'en-US-JennyNeural';
const encodedText = encodeURIComponent(text);
try {
const response = await fetch(`https://pvanand-audio-chat-indic.hf.space/auto-tts?text=${encodedText}`, {
method: 'GET',
headers: {
'accept': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.error('Error:', error);
return null;
}
},
toggleAudio(index) {
const message = this.messages[index];
if (this.currentAudio && this.currentAudio !== message.audioElement) {
this.currentAudio.pause();
this.messages.forEach(m => {
if (m.audioElement === this.currentAudio) {
m.isPlaying = false;
}
});
}
if (!message.audioElement) {
message.audioElement = new Audio(message.audio);
message.audioElement.addEventListener('ended', () => {
message.isPlaying = false;
this.$forceUpdate();
});
}
if (message.isPlaying) {
message.audioElement.pause();
} else {
message.audioElement.play();
this.currentAudio = message.audioElement;
}
message.isPlaying = !message.isPlaying;
this.$forceUpdate();
},
copyMarkdownToClipboard(rawResponse) {
navigator.clipboard.writeText(rawResponse).then(() => {
// remove alert
}).catch(err => {
console.error('Failed to copy: ', err);
});
},
async downloadResponse(rawResponse, fileType) {
try {
const html = marked.parse(rawResponse);
await convertHtmlToFile(html, fileType);
} catch (error) {
console.error('Error downloading file:', error);
// You might want to show an error message to the user here
}
},
handleInput(event) {
console.log("Input event triggered", event.target.value); // For debugging
if (event.target.value === '/') {
console.log("Slash detected, showing tool options"); // For debugging
this.showToolOptions = true;
} else {
this.showToolOptions = false;
}
// Reset tool_call to 'auto' if input doesn't contain /web or /news
if (!event.target.value.includes('/web') && !event.target.value.includes('/news')) {
this.tool_call = 'auto';
}
},
selectTool(tool) {
if (tool === 'web') {
this.tool_call = 'web';
this.userInput = '/web ';
} else if (tool === 'news') {
this.tool_call = 'news';
this.userInput = '/news ';
} else {
this.tool_call = 'auto';
}
this.showToolOptions = false;
this.$nextTick(() => {
const inputElement = document.getElementById('user-input');
inputElement.focus();
inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length);
});
},
watch: {
userInput(newVal, oldVal) {
console.log("userInput changed", newVal); // For debugging
if (newVal === '/') {
this.showToolOptions = true;
} else {
this.showToolOptions = false;
}
}
},
toggleSnippet(index) {
this.$set(this.expandedSnippets, index, !this.expandedSnippets[index]);
},
},
mounted() {
this.resetConversation();
}
});
</script>
</body>
</html>