chatbot jsx
import React, { useState } from 'react';
import bsnl from './bsnl-logo.png';
import './App.css';
const LLAMA3_API_URL = 'http://localhost:11434/api/generate'; // Update this to your actual endpoint
const BsnlChatbot = () => {
const [isOpen, setIsOpen] = useState(false);
const [messages, setMessages] = useState([
{ text: 'How can I assist you today?', sender: 'bot' }
]);
const [inputText, setInputText] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSend = async () => {
if (!inputText.trim()) return;
const userMessage = { text: inputText, sender: 'user' };
const updatedMessages = [...messages, userMessage];
setMessages(updatedMessages);
setInputText('');
setIsLoading(true);
try {
const response = await fetch(LLAMA3_API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'llama3.2',
prompt: inputText,
stream: false
}),
});
const data = await response.json();
const botReply = data?.response || 'Sorry, no response from the model.';
setMessages([...updatedMessages, { text: botReply, sender: 'bot' }]);
} catch (err) {
console.error('Error talking to LLaMA:', err);
setMessages([...updatedMessages, {
text: 'Oops! Something went wrong.',
sender: 'bot'
}]);
} finally {
setIsLoading(false);
}
};
return (
<>
{!isOpen && (
<button className="chat-toggle-btn" onClick={() => setIsOpen(true)}>
<img src={bsnl} alt="BSNL Logo" />
<span>BSNL AI Helper</span>
</button>
)}
{isOpen && (
<div className="chatbot-container">
<div className="chatbot-header">
<img src={bsnl} alt="BSNL Logo" />
<h3>BSNL AI Assistant</h3>
<button className="close-chat-btn" onClick={() => setIsOpen(false)}>×</button>
</div>
<div className="chatbot-messages">
{messages.map((msg, index) => (
<div key={index} className={`chat-message ${msg.sender}`}>
{msg.text}
</div>
))}
{isLoading && (
<div className="chat-message bot">Typing...</div>
)}
</div>
<div className="chatbot-input">
<input
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Type your question..."
onKeyDown={(e) => e.key === 'Enter' && handleSend()}
/>
<button onClick={handleSend} disabled={isLoading}>Send</button>
</div>
</div>
)}
</>
);
};
export default BsnlChatbot;