Make this into gradio UI
from gradio_client import Client
import json

# Initialize the client by pointing to the Gradio Space
client = Client("yuntian-deng/ChatGPT4")

# Persistent conversation history
chatbot_history = []  # Stores full chat history

def chat_with_model(inputs, top_p=1.0, temperature=1.0, chat_counter=0):
    """
    Interact with the Gradio chatbot while maintaining memory.

    Args:
        inputs (str): User input message to the chatbot.
        top_p (float): Top-p (nucleus sampling) parameter for response creativity (default = 1.0).
        temperature (float): Temperature for randomness in response (default = 1.0).
        chat_counter (int): The number of interactions so far (used internally).

    Returns:
        tuple: (response_text, new_chat_counter, updated_chatbot_history)
            - response_text (str): The assistant's most recent reply (formatted as JSON).
            - new_chat_counter (int): Updated chat count.
            - updated_chatbot_history (list): Updated conversation history.
    """
    global chatbot_history  # Modify the global chatbot history within the function

    try:
        # Call Gradio API endpoint /predict with history
        result = client.predict(
            inputs,            # User's input
            top_p,             # Sampling nucleus parameter
            temperature,       # Model sampling temperature
            chat_counter,      # Current step count of chat
            chatbot_history,   # Previous conversation history
            api_name="/predict"  # Gradio endpoint's function name
        )
        
        # Parse Gradio-provided outputs
        updated_history = result[0]  # Chat history list of tuples [(user, bot), ...]
        new_chat_counter = result[1]  # Updated chat counter
        response_textbox_value = result[3]  # String output of the assistant's reply

        # Update the persistent history
        chatbot_history = updated_history

        # Extract the latest assistant response from the updated chat history
        if updated_history:
            response_text = updated_history[-1][1]  # Final assistant's message
        else:
            response_text = "No response received."
        
        return response_text, new_chat_counter, updated_history

    except Exception as e:
        print(f"Error interacting with the chatbot: {e}")
        return "Error during chatbot interaction.", chat_counter, chatbot_history


# Main function for essay writing
def create_essay():
    chat_counter = 0  # Start at 0 interactions

    # Collect user inputs for the essay
    title = input("Enter the title of your essay: ")
    content = input("Enter the content of your essay: ")
    age = input("Enter your age: ")
    native_lang = input('Enter your native language: ')

    # Construct the system prompt and user input
    system_prompt = """
You are a highly skilled and impartial essay evaluator. Your job is to read and evaluate essays based on specific criteria and provide a detailed score and feedback for each category. Each essay will be scored on the following predefined criteria:

1. **Content and Ideas**: Assesses the relevance, originality, depth, and clarity of the ideas presented.
2. **Structure and Organization**: Evaluates the logical flow, paragraphing, introduction, conclusion, and transitions between ideas.
3. **Language and Style**: Focuses on the vocabulary, tone, sentence variety, and appropriateness for the target audience.
4. **Grammar, Mechanics, and Spelling**: Analyzes the correctness of grammar, punctuation, spelling, and overall writing mechanics.
5. **Adherence to the Prompt**: Determines how well the essay addresses and fulfills the given prompt or topic.

For each category, you must:
- Assign a **score from 0 to 10** (0 = Inadequate, 10 = Exceptional).
- Provide a **brief explanation or justification** for the score to give constructive feedback to the writer.

After scoring each category:
- Calculate the **overall score** as the average of all category scores.
- Provide **general feedback** that summarizes the strengths of the essay and areas for improvement.

Return the evaluation in the following JSON format(Do not add triple backtick):

{
  "scores": {
    "content_and_ideas": {
      "score": <number>,
      "feedback": "<feedback text>"
    },
    "structure_and_organization": {
      "score": <number>,
      "feedback": "<feedback text>"
    },
    "language_and_style": {
      "score": <number>,
      "feedback": "<feedback text>"
    },
    "grammar_mechanics_and_spelling": {
      "score": <number>,
      "feedback": "<feedback text>"
    },
    "adherence_to_prompt": {
      "score": <number>,
      "feedback": "<feedback text>"
    }
  },
  "overall_score": <number>,
  "general_feedback": "<summary feedback text>"
}
    """

    
    user_input_data = f"""
{system_prompt}

USER)
{{
  "title": {title},
  "content": {content},
  "context": {{
    "age": {age},
    "native_language": {native_lang},
  }}
}}"""

    # Send the input to the chatbot
    assistant_reply, chat_counter, chatbot_history = chat_with_model(
        inputs=user_input_data,
        top_p=1.0,             # Default settings; adjust for creativity
        temperature=0.7,       # Slightly less randomness
        chat_counter=chat_counter
    )

    print(assistant_reply)
    
if __name__ == "__main__":
    print(create_essay())