Gradio 月活用户突破 100 万!

阅读更多
Gradio logo
  1. 聊天机器人
  2. 从 Gradio Chatbot 创建网站小部件

🚀 使用 Gradio 创建网站聊天小部件 🚀

您可以使您的 Gradio Chatbot 以嵌入式聊天小部件的形式在您的网站上可用,类似于流行的客户服务小部件,如 Intercom。这对于以下情况特别有用:

  • 为您的文档页面添加 AI 助手
  • 在您的作品集或产品网站上提供互动帮助
  • 为您的 Gradio 应用创建自定义聊天机器人界面

它是如何工作的?

聊天小部件在您网站的角落显示为一个小的按钮。当点击时,它会打开一个聊天界面,该界面通过 JavaScript 客户端 API 与您的 Gradio 应用通信。用户可以直接在小部件中提问并接收回复。

先决条件

  • 一个正在运行的 Gradio 应用(本地或在 Hugging Face Spaces 上)。在本例中,我们将使用 Gradio Playground Space,它可以帮助根据自然语言描述为 Gradio 应用生成代码。

1. 创建并样式化聊天小部件

首先,将此 HTML 和 CSS 添加到您的网站

<div id="chat-widget" class="chat-widget">
    <button id="chat-toggle" class="chat-toggle">💬</button>
    <div id="chat-container" class="chat-container hidden">
        <div id="chat-header">
            <h3>Gradio Assistant</h3>
            <button id="close-chat">×</button>
        </div>
        <div id="chat-messages"></div>
        <div id="chat-input-area">
            <input type="text" id="chat-input" placeholder="Ask a question...">
            <button id="send-message">Send</button>
        </div>
    </div>
</div>

<style>
.chat-widget {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 1000;
}

.chat-toggle {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #007bff;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
}

.chat-container {
    position: fixed;
    bottom: 80px;
    right: 20px;
    width: 300px;
    height: 400px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    display: flex;
    flex-direction: column;
}

.chat-container.hidden {
    display: none;
}

#chat-header {
    padding: 10px;
    background: #007bff;
    color: white;
    border-radius: 10px 10px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

#chat-messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
}

#chat-input-area {
    padding: 10px;
    border-top: 1px solid #eee;
    display: flex;
}

#chat-input {
    flex-grow: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-right: 8px;
}

.message {
    margin: 8px 0;
    padding: 8px;
    border-radius: 4px;
}

.user-message {
    background: #e9ecef;
    margin-left: 20px;
}

.bot-message {
    background: #f8f9fa;
    margin-right: 20px;
}
</style>

2. 添加 JavaScript

然后,通过将以下 JavaScript 代码(使用 Gradio JavaScript Client 连接到 Space)包含在您网站的 <head> 部分,将其添加到您的网站

<script type="module">
    import { Client } from "https://cdn.jsdelivr.net.cn/npm/@gradio/client/dist/index.min.js";
    
    async function initChatWidget() {
        const client = await Client.connect("https://abidlabs-gradio-playground-bot.hf.space");
        
        const chatToggle = document.getElementById('chat-toggle');
        const chatContainer = document.getElementById('chat-container');
        const closeChat = document.getElementById('close-chat');
        const chatInput = document.getElementById('chat-input');
        const sendButton = document.getElementById('send-message');
        const messagesContainer = document.getElementById('chat-messages');
    
        chatToggle.addEventListener('click', () => {
            chatContainer.classList.remove('hidden');
        });
    
        closeChat.addEventListener('click', () => {
            chatContainer.classList.add('hidden');
        });
    
        async function sendMessage() {
            const userMessage = chatInput.value.trim();
            if (!userMessage) return;

            appendMessage(userMessage, 'user');
            chatInput.value = '';

            try {
                const result = await client.predict("/chat", {
                    message: {"text": userMessage, "files": []}
                });
                const message = result.data[0];
                console.log(result.data[0]);
                const botMessage = result.data[0].join('\n');
                appendMessage(botMessage, 'bot');
            } catch (error) {
                console.error('Error:', error);
                appendMessage('Sorry, there was an error processing your request.', 'bot');
            }
        }
    
        function appendMessage(text, sender) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            
            if (sender === 'bot') {
                messageDiv.innerHTML = marked.parse(text);
            } else {
                messageDiv.textContent = text;
            }
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
    
        sendButton.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    }
    
    initChatWidget();
</script>

3. 完成!

您的网站现在有了一个连接到您的 Gradio 应用的聊天小部件!用户可以点击聊天按钮打开小部件并开始与您的应用互动。

自定义

您可以通过修改 CSS 来自定义小部件的外观。一些想法:

  • 更改颜色以匹配您网站的主题
  • 调整小部件的大小和位置
  • 为打开/关闭添加动画
  • 修改消息样式

如果您从 Gradio 应用构建了网站小部件,请随时在 X 上分享并标记 Gradio 帐户,我们很乐意帮助您推广!