react-chatbot-kit
react-chatbot-kit copied to clipboard
Generate answers on a server
How to post the questions to the server API and get answers back with this API design with MessageParser and ActionProvider?
This is straightforward to do if you're using nextjs. It is likely different if you're using other frameworks. I'm using nextjs so I have an API setup within pages/api
called chat.js
. This has the API logic I need, something like this.
async function chatRoute(req, res) {
const body = req.body;
//do some stuff
res.status(200).json({
role: "bot",
content: "a response from the bot",
});
}
export default chatRoute;
Then I call this within a function in my ActionProvider component, I send some JSON through and get JSON back which I then add to the messages in the chatbot:
const handleChat = async (newPrompt,) => {
const body = {
newPrompt: newPrompt,
};
const result = await fetchJson("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
let newMessages = [];
const botMessage = createChatBotMessage(result.content);
newMessages.push(botMessage);
setState((prev) => ({
...prev,
messages: [...prev.messages, ...newMessages],
}));
};
Within MessageParser:
const parse = (message) => {
actions.handleChat(message;
}
}