hi help me fix the following bug, the chatbot replies with a self generated conversation history in its response to my message to it, here is my code:

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 specializing +
         in cognitive behavioral therapy (CBT) and mindfulness exercises.  +
        Your goal is to help users through supportive, evidence-based  +
        techniques to manage mental health challenges. Engage in  +
        compassionate conversations, offering helpful CBT strategies such  +
        as identifying and reframing negative thoughts, and guide users  +
        through mindfulness exercises like deep breathing and grounding  +
        techniques.\n\n;


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

        const prompt = ${systemPrompt}${conversationPrompt}Assistant:;

        // 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 sec

        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") {
        // Removing prompt from generated text to extract the assistant's reply
          assistantReply = data.generated_text
              .replace(conversationPrompt, "").replace(systemPrompt, "").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(conversationPrompt, "")
              .replace(systemPrompt, "").trim();
        } else {
          console.error("Missing or invalid 'gen_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"});
      }
    },
);