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.
code
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
Assistant
Main function for essay writing
def create_essay():
chat_counter = 0 # Start at 0 interactions
code
# 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:
Content and Ideas: Assesses the relevance, originality, depth, and clarity of the ideas presented.
Structure and Organization: Evaluates the logical flow, paragraphing, introduction, conclusion, and transitions between ideas.
Language and Style: Focuses on the vocabulary, tone, sentence variety, and appropriateness for the target audience.
Grammar, Mechanics, and Spelling: Analyzes the correctness of grammar, punctuation, spelling, and overall writing mechanics.
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):
# 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())
To convert your Python script into a Gradio UI, we need to integrate your main functions (like the create_essay function) into a Gradio interface. Gradio is a Python library that provides you with easy tools to build user interfaces for interacting with models. Below is the Gradio implementation of your script:
python
import gradio as gr
from gradio_client import Client
# 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):
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(title, content, age, native_language):
global chatbot_history
chat_counter = 0 # Start at 0 interactions
# 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_language}"
}}
}}"""
# 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
)
return assistant_reply
# Gradio UI
title_input = gr.Textbox(label="Essay Title", placeholder="Enter the title of your essay here")
content_input = gr.Textbox(label="Essay Content", placeholder="Enter the content of your essay here", lines=5)
age_input = gr.Number(label="Age", value=18)
native_lang_input = gr.Textbox(label="Native Language", placeholder="Enter your native language")
output = gr.Textbox(label="Essay Evaluation", placeholder="The evaluation results will be displayed here.")
interface = gr.Interface(
fn=create_essay,
inputs=[title_input, content_input, age_input, native_lang_input],
outputs=output,
title="Essay Evaluator",
description="Enter your essay details, and the system will evaluate it based on specific criteria."
)
if __name__ == "__main__":
interface.launch()
Explanation:
Gradio Inputs/Outputs:
title_input captures the essay's title.
content_input captures the essay content.
age_input captures the user's age.
native_lang_input captures the user's native language.
output is where the evaluation results are displayed.
Gradio Interface:
The gr.Interface wraps the create_essay function and displays inputs/outputs interactively.
Output:
The assistant's evaluation response will be returned and displayed in the textbox labeled "Essay Evaluation."
Deploy:
Run the script, and it will start an interactive web interface where users can interactively evaluate essays.
To Run:
Ensure Gradio is installed (pip install gradio).
Run the script, and a local link will appear for accessing the UI.