How do I incorporate the reset chat API call from my backend server for an AI chatbot interface into my frontend, specifically triggered by clicking the button to start a new chat.

Backend:
<code>
import logging
import ast
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from gradio_client import Client


Configure logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


app = FastAPI()


Configure CORS

app.add_middleware(
    CORSMiddleware,
    allow_origins=[""],  # Allows all origins
    allow_credentials=True,
    allow_methods=[""],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)


Initialize the Gradio Client

client = Client("yuntian-deng/o1mini")


class Message(BaseModel):
    text: str


def extract_latest_response(raw_response):
    try:
        # Remove the log tags and extract the content
        content = raw_response.replace('\nINFO:root:Raw response from Gradio Client: ', '').replace('\n', '')





    # Parse the content as a Python tuple
    parsed_content = ast.literal_eval(content)
    
    # Extract the first element of the tuple (the list of messages)
    messages = parsed_content[0]
    
    # Get the last message in the list
    last_message = messages[-1]
    
    # The response is the second element of the last message tuple
    response = last_message[1]
    
    return response
except Exception as e:
    print(f"Error extracting response: {str(e)}")
    return None

@app.post("/api/chat")
async def chat(message: Message):
    try:
        logger.info(f"Received message: {message.text}")





    # Send the entire conversation history to the Hugging Face Space
    response = client.predict(str(message.text), api_name="/predict")
    logger.info(f"Raw response from Gradio Client: {response}")
    
    # Extract the latest response
    extracted_response = extract_latest_response(str(response))
    logger.info(f"Extracted response: {extracted_response}")
    
    return {"response": extracted_response}
except Exception as e:
    logger.error(f"Error processing chat request: {str(e)}", exc_info=True)
    raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/reset")
async def reset_chat():
    try:
        logger.info("Resetting chat...")
        # Call the reset endpoint of the Gradio client
        reset_response = client.predict(api_name="/reset_textbox")
        logger.info(f"Raw reset response from Gradio Client: {reset_response}")





    logger.info(f"Reset response: {reset_response}")
    return {"status": "Chat has been reset.", "response": reset_response}
except Exception as e:
    logger.error(f"Error resetting chat: {str(e)}", exc_info=True)
    raise HTTPException(status_code=500, detail="Failed to reset chat.")
</code>

Frontend:
<code>
// src/components/Sidebar.js
import React, { useContext } from 'react';
import { ChatContext } from '../context/ChatContext';
import { PlusIcon, TrashIcon } from '@heroicons/react/solid';
import { ThemeContext } from '../context/ThemeContext';


function Sidebar() {
  const {
    chats,
    currentChatId,
    setCurrentChatId,
    addChat,
    deleteChat,
  } = useContext(ChatContext);


  const { theme, toggleTheme } = useContext(ThemeContext);


  const handleSelectChat = (id) => {
    setCurrentChatId(id);
  };


  const handleNewChat = () => {
    addChat('New Chat');
  };


  const handleDeleteChat = (e, id) => {
    e.stopPropagation(); // Prevent triggering the chat selection
    deleteChat(id);
  };


  const handleGoHome = () => {
    setCurrentChatId(null);
  };


  return (
    


{/* Chatbot Name "Echo" at the top */}

Echo

  <div className="flex justify-between items-center mb-4">
    <h2 className="text-xl font-bold text-gray-800 dark:text-gray-200">Past Chats</h2>
    <button
      onClick={handleNewChat}
      className="p-2 bg-blue-500 text-white rounded hover:bg-blue-600"
      title="Start New Chat"
    >
      <PlusIcon className="h-5 w-5" />
    </button>
  </div>
  <ul className="flex-1 overflow-y-auto">
    {chats.length === 0 && (
      <li className="text-gray-500 dark:text-gray-400">No past chats.</li>
    )}
    {chats.map((chat) => (
      <li
        key={chat.id}
        className={`mb-2 cursor-pointer p-2 rounded flex justify-between items-center ${
          chat.id === currentChatId
            ? 'bg-blue-100 dark:bg-blue-900'
            : 'hover:bg-gray-100 dark:hover:bg-gray-700'
        }`}
        onClick={() => handleSelectChat(chat.id)}
      >
        <span className='text-black dark:text-white'>{chat.name}</span>
        <button
          onClick={(e) => handleDeleteChat(e, chat.id)}
          className="text-red-500 hover:text-red-700"
          title="Delete Chat"
        >
          <TrashIcon className="h-5 w-5" />
        </button>
      </li>
    ))}
  </ul>

  {/* Dark Mode Toggle at the bottom */}
  <div className="mt-4">
    <DarkModeToggle theme={theme} toggleTheme={toggleTheme} />
  </div>
</div>
);
}

function DarkModeToggle({ theme, toggleTheme }) {
return (

Dark Mode
onClick={toggleTheme}
className={relative inline-flex items-center h-6 rounded-full w-11 focus:outline-none transition-colors duration-200 ${ theme === 'dark' ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700' }}
>
Toggle Dark Mode
className={${ theme === 'dark' ? 'translate-x-6' : 'translate-x-1' } inline-block w-4 h-4 transform bg-white rounded-full transition-transform duration-200}
/>


);
}
export default Sidebar;
</code>

Example frontend api call code from message send call:
<code>
const handleSend = async () => {
    if (!message.trim() || !currentChatId) return;

    const userMessage = { sender: 'user', text: message };
    addMessage(currentChatId, userMessage);
    setMessage('');
    scrollToBottom();

    // Set typing indicator
    setIsTyping(true);

    // Send the message to the backend
    try {
      const response = await fetch('http://localhost:8000/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: formatMessageWithSystemPrompt(message, currentChat.systemPrompt) }),
      });
      const data = await response.json();
      const responseText = data.response;

      // Check if the response contains code blocks
      const codeMatch = responseText.match(/```(?:\w+\n)?([\s\S]*?)```/);
      if (codeMatch) {
        //setCodeContent(codeMatch[1]);
        //setIsCodeModalOpen(true);
      }

      const botMessage = { sender: 'bot', text: responseText };
      addMessage(currentChatId, botMessage);
      scrollToBottom();
    } catch (error) {
      console.error('Error:', error);
      const errorMessage = { sender: 'bot', text: 'Sorry, something went wrong. Please try again.' };
      addMessage(currentChatId, errorMessage);
      scrollToBottom();
    } finally {
      // Remove typing indicator
      setIsTyping(false);
    }
  };
</code>