import React, { useRef, useEffect, useState } from… · The Chat Archive
Explore / Programming import React, { useRef, useEffect, useState } from "react"; import { MdThumbDown,… Save Share Download ▾ Reportimport React, { useRef, useEffect, useState } from "react";
import { MdThumbDown, MdThumbUp } from "react-icons/md";
import axios from "axios";
import "./index.css";
import baseurl from "../../api/url";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { keycloak } from "../../../../keycloak";
const Chat = () => {
const bottomEl = useRef(null);
const [messages, setMessages] = useState(
JSON.parse(sessionStorage.getItem("hr_messages") || "[]")
);
const [query, setquery] = useState("");
const [disabled, makeDisabled] = useState(false);
// const [prompt, setprompt] = useState({ initital_prompt: "", new_prompt: "" });
// if (keycloak.authenticated){
// keycloak.loadUserInfo().then((data)=>{ console.log("This is from chat page", data)})
// console.log(keycloak.profile)
// }
useEffect(() => {
// Scroll to the bottom when the component mounts or whenever content changes
if (bottomEl.current) {
bottomEl.current.scrollTop = bottomEl.current.scrollHeight;
}
}, [messages]);
const sendChatRequest = async (mail) => {
// Using a callback with setMessages to ensure working with the updated state
console.log(mail);
const mail2 = mail;
var index = -1;
setMessages((prevMessages) => {
index = prevMessages.length;
console.log(mail);
const updatedMessages = [
...prevMessages,
{ message: mail2, prompt: query },
];
sessionStorage.setItem("hr_messages", JSON.stringify(updatedMessages));
console.log("setstate: ", updatedMessages);
return updatedMessages;
});
Show full message · 461 lines Assistant2024-12-04 11:33 UTC Copy response
@app.route("/welcome-message", methods=['POST'])
def welcome_message():
try:
data = request.get_json()
user_email = data['user_email']
bot_name = data['bot_name']
code Copy code
response = Response(get_welcome_message(bot_name=bot_name, user_email=user_email), mimetype="text/event-stream")
response.headers["X-Accel-Buffering"] = "no"
print(f"/welcome-message - Response Sent to user: {user_email}")
return response
except Exception as e:
print(f"/welcome-message - Response Not Sent to user: {user_email}")
This is the backend api code, we need to call this endpoint to get welcome message.
Assistant2024-12-04 11:34 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 2 (4 messages)
Language en
Conversation date Dec 4, 2024
Added to archive Nov 16, 2026
ID 01m7h42ajhj3e80ntyze7r2qnmSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 9655105f1544827ce4a5d8c8138b176c
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
console.log("justaftersetstate: ", messages);
var context_history = [];
for (var message of messages) {
context_history.push({ role: "user", content: message.message });
if (message.api_output) {
if (message.api_output.options) {
context_history.push({
role: "assistant",
content:
"Please select any options of the following: \n" +
message.api_output.options.files.toString(),
});
} else {
context_history.push({
role: "assistant",
content: message.api_output.text,
});
}
}
}
var context_file = "";
if (mail.startsWith("file: ")) {
context_file = mail.replace("file: ", "");
console.log("file_context: ", context_file);
for (var each_message of context_history.reverse()) {
if (each_message.role == "user") {
mail = each_message.content;
console.log("mymail:", mail);
break;
}
}
}
try {
setquery("");
const res = await fetch(baseurl + "/answer", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: mail,
history: context_history,
file: context_file !== "" ? context_file : undefined,
user_email: JSON.parse(localStorage.getItem("user")).email,
stream: true,
}),
});
if (res.status == 202) {
console.log("I am here");
const reader = res.body.getReader();
const decoder = new TextDecoder("utf-8");
const { value, done } = await reader.read();
const chunk = decoder.decode(value, { stream: true });
console.log(JSON.parse(chunk));
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
if (!updatedMessages[index].api_output) {
updatedMessages[index].api_output = { options: JSON.parse(chunk) };
}
sessionStorage.setItem(
"hr_messages",
JSON.stringify(updatedMessages)
);
return updatedMessages;
});
} else {
const reader = res.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
while (buffer.includes("\n\n")) {
const newlineIndex = buffer.indexOf("\n\n");
const chunk_part = buffer.slice(0, newlineIndex);
buffer = buffer.slice(newlineIndex + 1);
const chunk_part_reformatted = chunk_part
.trim()
.replace("data: ", "");
if (chunk_part_reformatted) {
// console.log(chunk_part);
try {
const chunk_part_json = JSON.parse(chunk_part_reformatted);
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
if (!updatedMessages[index].api_output) {
updatedMessages[index].api_output = { text: "" };
}
updatedMessages[index].api_output.text +=
chunk_part_json.text;
updatedMessages[index].api_output.answer_id =
chunk_part_json.conversationid;
updatedMessages[index].api_output.pages =
chunk_part_json.pages;
updatedMessages[index].api_output.link = chunk_part_json.link;
sessionStorage.setItem(
"hr_messages",
JSON.stringify(updatedMessages)
);
return updatedMessages;
});
} catch (error) {
console.error("Error parsing JSON:", error);
}
}
}
}
}
} catch (error) {
console.error("Error:", error);
}
const handleUserQueryChange = (query) => {
// Using a callback with setMessages to ensure working with the updated state
setquery(query.target.value);
};
const change_feedback = (item, index, feedback) => {
// Using a callback with setMessages to ensure working with the updated state
axios
.post(baseurl + "/change_feedback", {
feedback: feedback,
conversationid: item.api_output.answer_id,
})
.then((value) => {
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
updatedMessages[index].api_output.feedback = feedback;
return updatedMessages;
});
})
.catch((error) => alert("Some error occured"));
};
return (
HR-Docs
<button
className="ml-0.5 rounded-lg px-6 py-1 text-lg text-white"
// className="ml-4 rounded-lg bg-gradient-to-r from-orange-400 py-3 text-lg text-white rounded"
style={{
background: "linear-gradient(to right, #ff0000, #990000)",
color: "white",
padding: "5px 10px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
setMessages([]);
sessionStorage.setItem("hr_messages", "[]");
}}
>
Clear Chat
{messages.length !== 0 ? (
messages.map((item, index) => {
// color_feedback = ""
// if (item.api_output.feedback == "NEGATIVE"){
// color_feedback =
// }else if (item.api_output.feedback == "POSITIVE"){
// color_feedback =
// }
return (
{/* <p className="text-lg" style={{ whiteSpace: "pre-line" }}> /}
{/ {item.message} /}
{item.message}
{/ */}
{item.api_output !== undefined ? (
<>
{item.api_output?.text && (
<>
{item.api_output?.text}
<MdThumbUp
className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
style={{
color:
item.api_output.feedback == "POSITIVE"
? "green"
: "",
}}
onClick={() =>
change_feedback(item, index, "POSITIVE")
}
/>
<MdThumbDown
className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
style={{
color:
item.api_output.feedback == "NEGATIVE"
? "red"
: "",
}}
onClick={() =>
change_feedback(item, index, "NEGATIVE")
}
/>
</>
)}
{item.api_output?.options && (
<>
{"### " + item.api_output.options.messgage}
{item.api_output.options.files.length !== 0 ? (
item.api_output.options.files.map(
(fileitem, index) => {
return (
<>
<button
className="rounded-lg px-6 py-3 text-m text-white"
// className="ml-4 rounded-lg bg-gradient-to-r from-orange-400 py-3 text-lg text-white rounded"
style={{
background:
"linear-gradient(to right, #f2994a, #d94e44)",
color: "white",
padding: "10px 20px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
sendChatRequest(
"file: " + fileitem.toString()
);
}}
>
{fileitem.toString()}
</>
);
}
)
) : (
{"#Some error occured"}
)}
{item.api_output?.text}
<MdThumbUp
className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
style={{
color:
item.api_output.feedback == "POSITIVE"
? "green"
: "",
}}
onClick={() =>
change_feedback(item, index, "POSITIVE")
}
/>
<MdThumbDown
className="h-8 w-8 cursor-pointer opacity-0 transition-opacity duration-300 group-hover:opacity-100 sticky top-0"
style={{
color:
item.api_output.feedback == "NEGATIVE"
? "red"
: "",
}}
onClick={() =>
change_feedback(item, index, "NEGATIVE")
}
/>
</>
)}
code Copy code
{item.api_output?.pages !== undefined &&
item.api_output?.pages !== "NA" &&
!item.api_output?.text.includes("really sorry") ? (
<div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary">
<a
href={item.api_output?.link}
className="text-blueSecondary underline"
target="_blank"
>
<strong>{item.api_output?.pages}</strong>
</a>
</div>
) : (
<></>
)}
</>
) : (
<div className="group relative flex items-center">
<div className="flex items-center self-start rounded-xl rounded-tl bg-white py-4 px-6">
<div className="typing">
<div className="typing__dot"></div>
<div className="typing__dot"></div>
<div className="typing__dot"></div>
</div>
</div>
</div>
)}
</div>
);
})
) : (
<div className="default-text max-h-[76vh] text-2xl">
<p>Paste a query in textbox below.</p>
</div>
)}
{/* <div ref={bottomEl}></div> */}
</div>
<div className="h-[10%] flex items-center">
<div className="mr-2 w-full text-lg">
<textarea
id="body"
name="body"
className="mr-2 w-full rounded-lg border border-gray-300 px-4 py-3 text-lg"
placeholder="Enter your query..."
rows="1"
cols="50"
value={query}
onChange={handleUserQueryChange}
onKeyDown={(e) => {
if (e.key === "Enter" && e.shiftKey === false) {
e.preventDefault();
if (!(query === "")) {
sendChatRequest(query);
} else {
alert("Please enter query");
}
}
}}
></textarea>
</div>
<button
className="ml-0.5 rounded-lg px-6 py-3 text-lg text-white"
// className="ml-4 rounded-lg bg-gradient-to-r from-orange-400 py-3 text-lg text-white rounded"
style={{
background: "linear-gradient(to right, #f2994a, #d94e44)",
color: "white",
padding: "10px 20px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
if (!(query === "")) {
sendChatRequest(query);
} else {
alert("Please enter query");
}
}}
>
Send
</button>
</div>
</div>
I want that as our page is loaded, we call a backend api for displaying the message. after that the chat should continue as usual. if the chat is already there, then I dont want to show the welcome message
To implement the functionality of calling a backend API to display a welcome message upon loading the page, while ensuring that this welcome message is not shown if there are already messages in the chat, you'll need to modify your existing React component. Here’s a step-by-step guide to achieve this:
Create a Function to Fetch the Welcome Message:
You will need to create an asynchronous function to call your backend API and retrieve the welcome message.
Modify the useEffect Hook:
Use the useEffect hook to call the fetch function when the component mounts. Ensure it checks if there are existing messages before making the API call.
Add the Welcome Message to State:
You'll add the welcome message to your messages state so that it can be displayed like other messages in the chat.
Here's the updated Chat component code:
javascript Copy code
import React, { useRef, useEffect, useState } from "react";
import { MdThumbDown, MdThumbUp } from "react-icons/md";
import axios from "axios";
import "./index.css";
import baseurl from "../../api/url";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { keycloak } from "../../../../keycloak";
const Chat = () => {
const bottomEl = useRef(null);
const [messages, setMessages] = useState(
JSON.parse(sessionStorage.getItem("hr_messages") || "[]") || []
);
const [query, setquery] = useState("");
const [disabled, makeDisabled] = useState(false);
useEffect(() => {
// Scroll to the bottom when the component mounts or whenever content changes
if (bottomEl.current) {
bottomEl.current.scrollTop = bottomEl.current.scrollHeight;
}
// Fetch welcome message if no messages are present
if (messages.length === 0) {
fetchWelcomeMessage();
}
}, [messages]);
const fetchWelcomeMessage = async () => {
try {
const response = await axios.get(`${baseurl}/welcome`); // Replace with your actual API endpoint
if (response.data) {
// Add the welcome message to messages
setMessages((prevMessages) => {
const updatedMessages = [
...prevMessages,
{ message: response.data.message, prompt: "Welcome" },
];
sessionStorage.setItem("hr_messages", JSON.stringify(updatedMessages));
return updatedMessages;
});
}
} catch (error) {
console.error("Error fetching welcome message:", error);
}
};
const sendChatRequest = async (mail) => {
// Your existing sendChatRequest logic
// ...
};
const handleUserQueryChange = (query) => {
setquery(query.target.value);
};
const change_feedback = (item, index, feedback) => {
axios
.post(baseurl + "/change_feedback", {
feedback: feedback,
conversationid: item.api_output.answer_id,
})
.then((value) => {
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
updatedMessages[index].api_output.feedback = feedback;
return updatedMessages;
});
})
.catch((error) => alert("Some error occurred"));
};
return (
<div className="flex h-[89vh] flex-col">
<div className="text-lg flex justify-between">
<strong>HR-Docs</strong>
<button
className="ml-0.5 rounded-lg px-6 py-1 text-lg text-white"
style={{
background: "linear-gradient(to right, #ff0000, #990000)",
color: "white",
padding: "5px 10px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
setMessages([]);
sessionStorage.setItem("hr_messages", "[]");
}}
>
Clear Chat
</button>
</div>
<div
ref={bottomEl}
className="h-[80%] flex flex-col flex-grow overflow-y-auto"
>
{messages.length !== 0 ? (
messages.map((item, index) => (
<div key={index} className="flex flex-col space-y-4 p-6">
{/* User message */}
<div className="max-w-75p flex items-center self-end rounded-xl rounded-lg rounded-tr bg-blueSecondary py-4 px-6 text-white ">
<Markdown className="prose text-white" remarkPlugins={[remarkGfm]}>
{item.message}
</Markdown>
</div>
{item.api_output && (
<div className="group relative flex items-end">
{/* Assistant response */}
{item.api_output?.text && (
<div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary py-4 px-6">
<Markdown className="prose" remarkPlugins={[remarkGfm]}>
{item.api_output?.text}
</Markdown>
</div>
)}
{/* Feedback buttons */}
<MdThumbUp onClick={() => change_feedback(item, index, "POSITIVE")} />
<MdThumbDown onClick={() => change_feedback(item, index, "NEGATIVE")} />
</div>
)}
</div>
))
) : (
<div className="default-text max-h-[76vh] text-2xl">
<p>Paste a query in the textbox below.</p>
</div>
)}
</div>
<div className="h-[10%] flex items-center">
<div className="mr-2 w-full text-lg">
<textarea
id="body"
name="body"
className="mr-2 w-full rounded-lg border border-gray-300 px-4 py-3 text-lg"
placeholder="Enter your query..."
rows="1"
cols="50"
value={query}
onChange={handleUserQueryChange}
onKeyDown={(e) => {
if (e.key === "Enter" && e.shiftKey === false) {
e.preventDefault();
if (query.trim() !== "") {
sendChatRequest(query);
} else {
alert("Please enter a query");
}
}
}}
></textarea>
</div>
<button
className="ml-0.5 rounded-lg px-6 py-3 text-lg text-white"
style={{
background: "linear-gradient(to right, #f2994a, #d94e44)",
color: "white",
padding: "10px 20px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
if (query.trim() !== "") {
sendChatRequest(query);
} else {
alert("Please enter a query");
}
}}
>
Send
</button>
</div>
</div>
);
};
export default Chat;
Changes Made:
fetchWelcomeMessage Function: A new function is created to fetch the welcome message from the backend using Axios. Adjust the endpoint as needed.
useEffect Hook Modification: This hook calls fetchWelcomeMessage only if there are no messages in the state.
Session Storage Handling: The welcome message is stored in the session storage in the same way as other messages.
Conclusion
With this approach, the application will make an API call to fetch a welcome message when the component loads, provided there are no existing messages. This way, once the user interacts with the chat (e.g., by sending messages), the welcome message will not be displayed again.
Show full message · 207 lines To integrate the Flask backend API endpoint /welcome-message that you provided into your existing React Chat component, you'll want to slightly modify the function fetchWelcomeMessage in your code. This change will ensure that the function correctly sends a POST request to the /welcome-message endpoint and retrieves the welcome message using the required parameters.
Here's the updated fetchWelcomeMessage function:
Modify the Fetch Function: Update the way the welcome message is fetched in your React component, so it uses the new endpoint and handles the JSON response properly.
Updated Code Snippet for the fetchWelcomeMessage Function:
javascript Copy code
const fetchWelcomeMessage = async () => {
// Retrieve user email and bot name if they are stored
const userEmail = JSON.parse(localStorage.getItem("user")).email;
const botName = "HR-Docs"; // Set your bot name here or retrieve from somewhere
try {
const response = await axios.post(`${baseurl}/welcome-message`, {
user_email: userEmail,
bot_name: botName,
});
// Assuming your backend returns the message correctly
if (response.data) {
setMessages((prevMessages) => {
const updatedMessages = [
...prevMessages,
{ message: response.data.message, prompt: "Welcome" },
];
sessionStorage.setItem("hr_messages", JSON.stringify(updatedMessages));
return updatedMessages;
});
}
} catch (error) {
console.error("Error fetching welcome message:", error);
}
};
Full Integration of the React Component:
Here's how your complete Chat component should look, integrated with the new fetchWelcomeMessage function.
Key Changes and Considerations:
POST Request: The fetchWelcomeMessage function now sends a POST request to the /welcome-message endpoint with the necessary parameters.
Expected Response Structure: The code assumes that the API response will include a message in response.data.message. You may want to confirm that this matches the API you're implementing.
Error Handling: Basic error handling is included to log if there’s an error fetching the welcome message.
User Email and Bot Name Retrieval: Make sure that the user email is stored in local storage before calling the API. You may want to adjust the logic accordingly if the user email or bot name is managed differently in your application.
This setup should correctly fetch and display a welcome message upon loading the chat component.
Show full message · 245 lines Copy first response
Not yet included in a published release.
import React, { useRef, useEffect, useState } from "react";
import { MdThumbDown, MdThumbUp } from "react-icons/md";
import axios from "axios";
import "./index.css";
import baseurl from "../../api/url";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { keycloak } from "../../../../keycloak";
const Chat = () => {
const bottomEl = useRef(null);
const [messages, setMessages] = useState(
JSON.parse(sessionStorage.getItem("hr_messages") || "[]") || []
);
const [query, setquery] = useState("");
const [disabled, makeDisabled] = useState(false);
useEffect(() => {
// Scroll to the bottom when the component mounts or whenever content changes
if (bottomEl.current) {
bottomEl.current.scrollTop = bottomEl.current.scrollHeight;
}
// Fetch welcome message if no messages are present
if (messages.length === 0) {
fetchWelcomeMessage();
}
}, [messages]);
const fetchWelcomeMessage = async () => {
// Retrieve user email and bot name if they are stored
const userEmail = JSON.parse(localStorage.getItem("user")).email;
const botName = "HR-Docs"; // Set your bot name here or retrieve from somewhere
try {
const response = await axios.post(`${baseurl}/welcome-message`, {
user_email: userEmail,
bot_name: botName,
});
// Assuming your backend returns the message correctly in response.data
if (response.data) {
setMessages((prevMessages) => {
const updatedMessages = [
...prevMessages,
{ message: response.data.message, prompt: "Welcome" },
];
sessionStorage.setItem("hr_messages", JSON.stringify(updatedMessages));
return updatedMessages;
});
}
} catch (error) {
console.error("Error fetching welcome message:", error);
}
};
const sendChatRequest = async (mail) => {
// Your existing sendChatRequest logic
// ...
};
const handleUserQueryChange = (query) => {
setquery(query.target.value);
};
const change_feedback = (item, index, feedback) => {
axios
.post(baseurl + "/change_feedback", {
feedback: feedback,
conversationid: item.api_output.answer_id,
})
.then((value) => {
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
updatedMessages[index].api_output.feedback = feedback;
return updatedMessages;
});
})
.catch((error) => alert("Some error occurred"));
};
return (
<div className="flex h-[89vh] flex-col">
<div className="text-lg flex justify-between">
<strong>HR-Docs</strong>
<button
className="ml-0.5 rounded-lg px-6 py-1 text-lg text-white"
style={{
background: "linear-gradient(to right, #ff0000, #990000)",
color: "white",
padding: "5px 10px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
setMessages([]);
sessionStorage.setItem("hr_messages", "[]");
}}
>
Clear Chat
</button>
</div>
<div
ref={bottomEl}
className="h-[80%] flex flex-col flex-grow overflow-y-auto"
>
{messages.length !== 0 ? (
messages.map((item, index) => (
<div key={index} className="flex flex-col space-y-4 p-6">
{/* User message */}
<div className="max-w-75p flex items-center self-end rounded-xl rounded-lg rounded-tr bg-blueSecondary py-4 px-6 text-white ">
<Markdown className="prose text-white" remarkPlugins={[remarkGfm]}>
{item.message}
</Markdown>
</div>
{item.api_output && (
<div className="group relative flex items-end">
{/* Assistant response */}
{item.api_output?.text && (
<div className="flex items-center self-start rounded-xl rounded-lg rounded-tl bg-lightPrimary py-4 px-6">
<Markdown className="prose" remarkPlugins={[remarkGfm]}>
{item.api_output?.text}
</Markdown>
</div>
)}
{/* Feedback buttons */}
<MdThumbUp onClick={() => change_feedback(item, index, "POSITIVE")} />
<MdThumbDown onClick={() => change_feedback(item, index, "NEGATIVE")} />
</div>
)}
</div>
))
) : (
<div className="default-text max-h-[76vh] text-2xl">
<p>Paste a query in the textbox below.</p>
</div>
)}
</div>
<div className="h-[10%] flex items-center">
<div className="mr-2 w-full text-lg">
<textarea
id="body"
name="body"
className="mr-2 w-full rounded-lg border border-gray-300 px-4 py-3 text-lg"
placeholder="Enter your query..."
rows="1"
cols="50"
value={query}
onChange={handleUserQueryChange}
onKeyDown={(e) => {
if (e.key === "Enter" && e.shiftKey === false) {
e.preventDefault();
if (query.trim() !== "") {
sendChatRequest(query);
} else {
alert("Please enter a query");
}
}
}}
></textarea>
</div>
<button
className="ml-0.5 rounded-lg px-6 py-3 text-lg text-white"
style={{
background: "linear-gradient(to right, #f2994a, #d94e44)",
color: "white",
padding: "10px 20px",
borderRadius: "5px",
border: "none",
cursor: "pointer",
}}
onClick={() => {
if (query.trim() !== "") {
sendChatRequest(query);
} else {
alert("Please enter a query");
}
}}
>
Send
</button>
</div>
</div>
);
};
export default Chat;