retrieving information from a previous chat

Programmers, Engineers!
I am having this issue trying to retrieve data in the same session during chatting with this chat bot

@app.route("/chat", methods=["POST"])
def chat():
    try:
        user_input = request.json.get("message", "")
        session_id = request.json.get("session_id", str(uuid.uuid4()))  # Generate a new session ID if not provided
        user_name = request.json.get("name", "User")  # Extract user name if provided

        # Store or update the user's name in the conversation model
        conversation = Conversation.query.filter_by(session_id=session_id).first()
        if conversation:
            conversation.user_name = user_name
            conversation.user_message = user_input
        else:
          conversation = Conversation(session_id=session_id, user_name=user_name, user_message=user_input, bot_reply="")
            db.session.add(conversation)
        db.session.commit()

        # Retrieve conversation history
        conversations = Conversation.query.filter_by(session_id=session_id).all()
        conversation_history = [c.user_message for c in conversations]

        # Retrieve user name from session
        user_name = session.get("name", "User")

        # Generate response using OpenAI's API with a system message
        app.logger.info("Generating response with ChatGPT...")
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": f"You are a medical assistant. Your name is {user_name}. Provide accurate medical information and advice. If you are unsure about a medical issue, advise the user to consult a healthcare professional."},
                    {"role": "system", "content": "Conversation history: " + ", ".join(conversation_history)},
                    {"role": "user", "content": user_input}
                ],
                max_tokens=300,
                temperature=0.7
            )
            bot_reply = response['choices'][0]['message']['content'].strip()
            app.logger.info(f"ChatGPT reply: {bot_reply}")
        except Exception as e:
            app.logger.error(f"Error generating response with ChatGPT: {e}")
            bot_reply = "Error: Unable to generate response."

        # Update and store the conversation in the database
        app.logger.info("Updating conversation in database...")
        conversation.bot_reply = bot_reply
        db.session.commit()
        app.logger.info("Conversation updated successfully.")

        return jsonify({"response": bot_reply, "session_id": session_id, "name": user_name})

    except Exception as e:
        app.logger.error(f"Error processing request: {e}")
        return jsonify({"response": "Sorry, there was an error processing your request."})

This is the chat i had with the AI:
Hi there my name is Osama

Hello, Osama! How can I assist you with your medical questions or concerns today?

what is my name

I’m sorry, I don’t have access to your personal information such as your name. How can I assist you today?

Me: Hi there my name is osamah

ChatBot: Hello, Osamah! How can I assist you today?

Me: what is my name

ChatBot: I’m sorry, but I don’t have access to that information. How can I assist you today?

this is my app.js that i spent hours trying to find if id does not run the session correctly:

function App() {
  const [chatHistory, setChatHistory] = useState([]);
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [sessionId, setSessionId] = useState('');
  const [userName, setUserName] = useState('');

  // Initialize a new session ID when the component mounts
  useEffect(() => {
    const initSession = async () => {
      try {
        const response = await axios.post('http://localhost:5000/chat', { message: '' });
        setSessionId(response.data.session_id);
        console.log('Session initialized:', response.data);
      } catch (error) {
        console.error('Error initializing session:', error);
      }
    };
    initSession();
  }, []);

  const handleSendMessage = async () => {
    if (message.trim() === '' || !sessionId) return;

    setChatHistory([...chatHistory, { role: 'user', content: message }]);

    try {
      setLoading(true);
      const response = await axios.post('http://localhost:5000/chat', {
        message: message,
        session_id: sessionId,
        name: userName
      });
      console.log('Response from server:', response.data);
      setChatHistory(prev => [
        ...prev,
        { role: 'assistant', content: response.data.response }
      ]);
    } catch (error) {
      console.error('Error fetching data:', error);
      setChatHistory(prev => [
        ...prev,
        { role: 'assistant', content: 'Error: Unable to get a response.' }
      ]);
    } finally {
      setLoading(false);
      setMessage('');
    }
  };

  const handleUserNameChange = (event) => {
    setUserName(event.target.value);
  };