Skip to content

Instantly share code, notes, and snippets.

@pyoneerC
Created August 12, 2024 13:18
Show Gist options
  • Save pyoneerC/495a4d0408c0320186f15d0aad33e01a to your computer and use it in GitHub Desktop.
Save pyoneerC/495a4d0408c0320186f15d0aad33e01a to your computer and use it in GitHub Desktop.
"use client"
import React, { useState } from 'react';
const Chatbot = () => {
const [input, setInput] = useState('');
const [messages, setMessages] = useState([
{ role: 'system', content: 'dresan es el goat' }
]);
const [loading, setLoading] = useState(false);
const handleInputChange = (e) => {
setInput(e.target.value);
};
const sendMessage = async () => {
if (input.trim() === '') return;
setLoading(true);
const userMessage = { role: 'user', content: input };
const newMessages = [...messages, userMessage];
setMessages(newMessages);
try {
const response = await fetch('https://api.groq.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GROQ_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'llama3-70b-8192',
messages: newMessages,
max_tokens: 50,
stop: ['\n'],
temperature: 1.2,
}),
});
const data = await response.json();
const botMessage = {
role: 'assistant',
content: data.choices[0].message.content,
};
setMessages((prevMessages) => [...prevMessages, botMessage]);
} catch (error) {
console.error('Error fetching AI response:', error);
const errorMessage = { role: 'assistant', content: 'Sorry, something went wrong. Please try again later.' };
setMessages((prevMessages) => [...prevMessages, errorMessage]);
}
setInput('');
setLoading(false);
};
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
sendMessage();
}
};
return (
<div className="chatbot-container">
<div className="chatbox">
{messages.map((message, index) => (
<div key={index} className={`message ${message.role}`}>
{message.content}
</div>
))}
{loading && <div className="message assistant">Loading...</div>}
</div>
<input
type="text"
value={input}
onChange={handleInputChange}
onSubmit={sendMessage}
placeholder="Type your message..."
className="chat-input"
/>
<button onClick={sendMessage} disabled={loading} className="send-button">
Send
</button>
</div>
);
};
export default Chatbot;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment