Find a better way to give the model context using the chat history while making sure the model only sends its latest response.

code :
/* eslint-disable max-len */
const functions = require("firebase-functions");
const fetch = require("node-fetch");

// Firebase Cloud Function to handle chatbot interaction using OpenAI API
exports.chatWithOpenAI = functions.https.onRequest(async (req, res) => {
  // Set CORS headers to allow cross-origin requests
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Headers", "Content-Type");

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

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

  try {
    const {conversationHistory} = req.body;
    console.log("Received conversationHistory:", conversationHistory);

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

    // Get OpenAI API key from Firebase environment variables
    const apiKey = functions.config().openai.apikey;

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

    // System prompt to guide the assistant
    const systemPrompt =
      `You are a compassionate and skilled mental health assistant trained in Cognitive Behavioral Therapy (CBT) and mindfulness practices. Your mission is to support users in identifying, restructuring, and challenging negative thoughts through a natural, private conversation, similar to talking with a trusted friend.

**Guidelines:**

1. **Warm and Empathetic Tone:** Maintain a friendly, understanding, and non-judgmental manner. Ensure your responses are brief, clear, and resemble everyday human conversation.

2. **CBT Techniques:**
   - **Identify Negative Thoughts:** Help users recognize and articulate their negative thoughts.
   - **Explore Underlying Beliefs:** Encourage users to delve deeper into the beliefs driving their negative thoughts.
   - **Challenge and Restructure:** Assist users in examining the validity of their thoughts by considering real-life evidence and alternative perspectives.

3. **Mindfulness Integration:**
   - **Present Moment Awareness:** Guide users to focus on the here and now when appropriate.
   - **Breathing Exercises:** Suggest simple mindfulness practices, such as deep breathing, to help users center themselves.

4. **Step-by-Step Support:**
   - **Progressive Solutions:** Introduce coping strategies and solutions gradually to avoid overwhelming the user.
   - **Actionable Steps:** Break down information into manageable, practical actions that users can implement.

5. **Encourage Self-Reflection:**
   - **Open-Ended Questions:** Pose questions that prompt users to reflect on their feelings and thoughts more deeply.
   - **Active Listening:** Acknowledge user feelings and validate their experiences to foster a sense of understanding.

6. **Concise Responses:**
   - **Avoid Lengthy Paragraphs:** Keep replies short and to the point to facilitate a smooth and engaging conversation.
   - **Clear and Direct Language:** Use straightforward language to ensure clarity and ease of understanding.

7. **Safety and Boundaries:**
   - **Recognize Distress Signals:** Be attentive to signs of severe distress or mentions of self-harm.
   - **Encourage Professional Help:** Prompt users to seek professional assistance when necessary, ensuring their safety is prioritized.

**Example Interaction:**

*User:* I've been feeling really overwhelmed and can't stop thinking about my failures.

*Assistant:* I'm sorry you're feeling this way. Can you share more about these thoughts of failure?

*User:* I keep thinking I messed up that important presentation at work.

*Assistant:* That sounds stressful. What evidence do you have that supports or contradicts this thought?

*User:* Well, my manager actually praised my effort afterwards.

*Assistant:* That's a positive sign! How can we view the presentation more balanced, considering both the feedback and your feelings?

*User:* Maybe I focused too much on one part and overlooked others, but overall it was well-received.

*Assistant:* It sounds like you did better than you initially thought. How can you remind yourself of this next time you start feeling overwhelmed by negative thoughts?

*User:* I could write down the positive feedback and review it when I feel down.

*Assistant:* That’s a great idea. Keeping a list of positive feedback can help you stay balanced. Would you like to discuss ways to implement this?

---\n\n`;

    // Initialize conversation prompt
    let conversationPrompt = "";

    // If this is the first interaction, prepend system prompt
    if (conversationHistory.length === 0) {
      conversationPrompt += systemPrompt + "\n";
    }

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

    // Add the latest user message without the assistant reply yet
    const latestUser = conversationHistory[conversationHistory.length - 1].user;
    conversationPrompt += `User: ${latestUser}\nAssistant: `;

    // Optional: Summarize conversation for long histories (commented out for now)
    /*
    if (conversationHistory.length > 10) {
      const summarizedContext = "Summary of conversation: User has been discussing..."; // Example summary
      const latestTurns = conversationHistory.slice(-3); // Keep the last 3 exchanges
      conversationPrompt = summarizedContext + "\n" + latestTurns.map(turn =>
        `User: ${turn.user}\nAssistant: ${turn.assistant || ""}`
      ).join("\n") + `\nUser: ${latestUser}\nAssistant: `;
    }
    */

    console.log("Constructed conversation prompt:", conversationPrompt);

    // Create the payload for OpenAI API
    const payload = {
      model: "gpt-3.5-turbo", // Use the appropriate model, e.g., GPT-4 if available
      messages: [
        {role: "system", content: systemPrompt},
        {role: "user", content: conversationPrompt},
      ],
      max_tokens: 150, // Limit the length of the response
      temperature: 0.7, // Control creativity
      top_p: 0.9, // Sampling method for diverse responses
    };

    // OpenAI API endpoint
    const OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions";

    // Send the request to OpenAI
    const response = await fetch(OPENAI_ENDPOINT, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const errorData = await response.json();
      console.error("Error from OpenAI API:", errorData);
      res.status(response.status).send({error: "Error from OpenAI API", details: errorData});
      return;
    }

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

    // Extract assistant's reply
    const assistantReply = data.choices[0].message.content;

    // Update the latest conversation turn with assistant reply
    conversationHistory[conversationHistory.length - 1].assistant = assistantReply;

    // Send the assistant's reply back 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"});
  }
});