Build a NodeJS Chat App
Steps (and GitHub repo) to build a NodeJS Chat app with Corcel
Would you like to add a genAI chat app to your NodeJS website? look no further. IN this tutorial, we'll build a basic chat application using Corcel's APIs.
TL;dr: There's a Github repo with the code in it.
To use the application, you'll need an API Key .
Create a .env file, and save your API key in the.env file:
CORCEL_KEY=(your key here)
Backend
The backend has a listener on port 3000:
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
But the meat of the backend is the sendMessage
endpoint:
app.post('/sendMessage', async (req, res) => {
const conversationHistory = req.body.messages;
console.log(conversationHistory);
// Set up the options for the Corcel API request
const options = {
method: 'POST',
url: 'https://api.corcel.io/v1/text/cortext/chat',
headers: {
accept: 'application/json',
'content-type': 'application/json',
Authorization: process.env.CORCEL_KEY // Replace with your API key
},
data: {
model: 'cortext-ultra',
stream: false,
top_p: 1,
temperature: 0.0001,
max_tokens: 4096,
messages: conversationHistory
}
};
try {
// Send the conversation history to the Corcel API and get the response
const response = await axios.request(options);
// Extract the 'content' from the response
const content = response.data[0].choices[0].delta.content;
// Send the 'content' back to the client
res.json({ content });
} catch (error) {
console.error(error);
res.status(500).send('An error occurred while processing your message.');
}
});
When data arrives at the sendMessage endpoint, we extract the messages. We then set up an axios POST call to the cortext/chat
endpoint at Corcel. We use the .env file to safely store our API key (and not accidentally sharing to Github).
When the response comes back, we extract the generated response, and return it to the webpage.
Frontend
The head of the HTML has some CSS which I'll leave out here, but it sets the pretty colours and look and feel.
The actual HTML of the page is super basic - a div for the messages, and a form where the user can create a message to send to the API.
The JavaScript creates an array for conversationHistory
, and when a message is sent -adds the user's message to the the messages
div, and to the array. The entire conversation Hisstory is sent to the backend - so that the API knows the full context of the conversation.
When the response comes back it is added to messages
and the conversationHistory
array.
<body>
<h1> NodeJS Cortext sample app </h1>
<div id="chat">
<div id="messages"></div>
<input type="text" id="messageInput">
<button onclick="sendMessage()">Send</button>
</div>
<script>
let conversationHistory = [];
function sendMessage() {
const messageInput = document.getElementById('messageInput');
const userMessage = messageInput.value;
messageInput.value = '';
// Add the user's message to the conversation history
conversationHistory.push({ role: 'user', content: userMessage });
console.log(conversationHistory);
// Display the user's message
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += `<div><b>User</b>: ${userMessage}</div>`;
// Send the conversation history to the server
fetch('/sendMessage', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ messages: conversationHistory })
})
.then(response => response.json())
.then(data => {
// Add the assistant's response to the conversation history
conversationHistory.push({ role: 'assistant', content: data.content });
// Display the assistant's response
messagesDiv.innerHTML += `<div><b>Assistant</b>: ${data.content}</div>`;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
And that's all there is to it!
Updated 9 months ago