please fix my code, it works but the bot returns a self generated conversation history in one block.

here is the chatpage.js:
import React, { useState, useEffect, useContext, useRef } from 'react';
import { AuthContext } from '../AuthContext';
import { TextField, Button, Paper, Typography } from '@mui/material';
import SendIcon from '@mui/icons-material/Send';
import { styled } from '@mui/system';

// Define your custom styled components
const Root = styled('div')(({ theme }) => ({
  height: '100vh',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: theme.palette.background.default,
}));

const ChatContainer = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(4),
  textAlign: 'center',
  width: '400px',
  height: '500px',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'space-between',
  overflowY: 'auto',
}));

const Title = styled(Typography)(({ theme }) => ({
  marginBottom: theme.spacing(2),
}));

const MessageContainer = styled('div')({
  marginTop: 16,
  flexGrow: 1,
  display: 'flex',
  flexDirection: 'column',
  overflowY: 'auto',
});

const Message = styled(Typography)(({ sender, theme }) => ({
  alignSelf: sender === 'user' ? 'flex-end' : 'flex-start',
  backgroundColor:
    sender === 'user' ? theme.palette.primary.main : theme.palette.grey[200],
  color:
    sender === 'user'
      ? theme.palette.primary.contrastText
      : theme.palette.text.primary,
  padding: theme.spacing(1),
  borderRadius: theme.spacing(1),
  marginBottom: theme.spacing(1),
  maxWidth: '75%',
}));

const InputContainer = styled('div')(({ theme }) => ({
  display: 'flex',
  gap: theme.spacing(1),
  marginTop: theme.spacing(2),
}));

const TextInput = styled(TextField)(({ theme }) => ({
  flexGrow: 1,
}));

const SendButton = styled(Button)(({ theme }) => ({
  flexShrink: 0,
}));

function ChatPage() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const { currentUser } = useContext(AuthContext);

  const messagesEndRef = useRef(null);

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSend = async () => {
    if (input.trim() === '') return;
    const userMessage = { sender: 'user', text: input };
    setMessages((prev) => [...prev, userMessage]);

    // Prepare conversation history for the backend
    const conversationHistory = [];
    for (let i = 0; i < messages.length; i += 2) {
      const userMsg = messages[i]?.text || '';
      const assistantMsg = messages[i + 1]?.text || '';
      conversationHistory.push({ user: userMsg, assistant: assistantMsg });
    }
    // Add the latest user message without an assistant reply yet
    conversationHistory.push({ user: input, assistant: '' });

    try {
      // Call your Firebase Cloud Function
      const response = await fetch(
        'https://us-central1-mind-gardener.cloudfunctions.net/chatWithHuggingFace',
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ conversationHistory }),
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        console.error('Error response from Cloud Function:', errorData);
        throw new Error(errorData.error || 'Server error');
      }

      const result = await response.json();
      console.log('Response from Firebase Function:', result);

      const botReply = result.reply || 'No response from bot';

      const botMessage = { sender: 'bot', text: botReply };
      setMessages((prev) => [...prev, botMessage]);
    } catch (error) {
      console.error('Chatbot error:', error);
      setMessages((prev) => [
        ...prev,
        { sender: 'bot', text: 'Sorry, there was an error.' },
      ]);
    }

    setInput('');
  };

  return (
    <Root>
      <Title variant="h4">MindGarden</Title>
      <ChatContainer>
        <MessageContainer>
          {messages.map((msg, index) => (
            <Message key={index} sender={msg.sender}>
              {msg.text}
            </Message>
          ))}
          <div ref={messagesEndRef} />
        </MessageContainer>
        <InputContainer>
          <TextInput
            variant="outlined"
            placeholder="Type your message..."
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') handleSend();
            }}
          />
          <SendButton variant="contained" color="primary" onClick={handleSend}>
            <SendIcon />
          </SendButton>
        </InputContainer>
      </ChatContainer>
    </Root>
  );
}

export default ChatPage;

here is my index.js:
/* eslint-disable max-len */
const functions = require("firebase-functions");

exports.chatWithHuggingFace = functions.https.onRequest(
    async (req, res) => {
    // Handle CORS
      res.set("Access-Control-Allow-Origin", "*");
      res.set("Access-Control-Allow-Headers", "Content-Type");

      // Exit early if preflight request
      if (req.method === "OPTIONS") {
        res.status(204).send("");
        return;
      }

      // Only accept POST requests
      if (req.method !== "POST") {
        res.status(405).send({error: "Only POST requests are accepted"});
        return;
      }

      try {
        const {conversationHistory} = req.body;

        if (!conversationHistory) {
          res.status(400).send({
            error: "Missing \"conversationHistory\" in request body",
          });
          return;
        }

        const apiKey = functions.config().huggingface?.apikey;

        if (!apiKey) {
          res.status(500).send({
            error: "Hugging Face API key is not configured",
          });
          return;
        }

        // Build the system prompt
        const systemPrompt =
        `You are "MindGarden", an empathetic mental health agent. Your goal ` +
        `is to provide supportive and understanding responses to users who ` +
        `might be experiencing mental health challenges. Engage in a ` +
        `compassionate and respectful conversation with the user.\n\n`;

        // Build the conversation prompt from conversation history
        let conversationPrompt = "";
        conversationHistory.forEach((turn) => {
          conversationPrompt += `User: ${turn.user}\nAssistant: ${turn.assistant}\n`;
        });

        const prompt = `${systemPrompt}${conversationPrompt}User: `; // Add "User: " to the end for the next user input

        // Create the payload for Hugging Face API
        const payload = {
          inputs: prompt,
          parameters: {
            max_new_tokens: 150,
            temperature: 0.7,
            top_p: 0.9,
            repetition_penalty: 1.1,
          },
        };

        // Set up a timeout for the request
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), 30000); // 30 seconds

        let response;
        try {
        // Make the request to the Hugging Face API
          response = await fetch(
              "https://d9itacbt2nk3soa3.us-east-1.aws.endpoints.huggingface.cloud",
              {
                method: "POST",
                headers: {
                  "Authorization": `Bearer ${apiKey}`,
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(payload),
                signal: controller.signal,
              },
          );
          clearTimeout(timeout); // Clear the timeout if successful
        } catch (error) {
          if (error.name === "AbortError") {
            console.error("Request timed out");
            res.status(504).send({error: "Request to Hugging Face timed out"});
            return;
          } else {
            console.error("Fetch error:", error);
            res.status(500).send({error: "Fetch error"});
            return;
          }
        }

        // Handle API errors
        if (!response.ok) {
          const errorData = await response.text();
          console.error("Error from Hugging Face API:", errorData);
          res.status(response.status).send({
            error: "Error from Hugging Face API",
            details: errorData,
          });
          return;
        }

        // Process the response from Hugging Face
        const data = await response.json();
        console.log("Data from Hugging Face API:", data);

        // Check if the generated text is present and valid
        let assistantReply;

        if (data.generated_text && typeof data.generated_text === "string") {
          // Extract the assistant's reply by removing the prompt and trimming whitespace.
          assistantReply = data.generated_text.replace(prompt, "").trim();
        } else if (
          Array.isArray(data) &&
        data.length > 0 &&
        data[0].generated_text
        ) {
          // Handle cases where the response is an array
          assistantReply = data[0].generated_text.replace(prompt, "").trim();
        } else {
          console.error("Missing or invalid 'generated_text' from Hugging Face API");
          res.status(500).send({
            error: "Invalid response from Hugging Face API",
          });
          return;
        }

        // Send the assistant's reply to the client
        res.status(200).send({reply: assistantReply});
      } catch (error) {
        console.error("Error in Cloud Function:", error);
        res.status(500).send({error: "Internal server error"});
      }
    },
);