Make this into gradio ui
import requests
from gradio_client import Client

# GPT-4 API Client Initialization
client = Client("yuntian-deng/ChatGPT4")

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

def extract_doc_id(url_or_id):
    """
    Extract the Document ID from a full Google Docs URL or return it as is if it's already an ID.
    """
    if "docs.google.com" in url_or_id:
        # Extract the Document ID from the URL
        start = url_or_id.find("/d/") + 3
        end = url_or_id.find("/", start)
        return url_or_id[start:end]
    return url_or_id  # Assume it's already a Document ID


def fetch_public_google_doc(doc_id):
    """
    Fetch the content of a public Google Doc using its Document ID.

    Args:
        doc_id (str): The ID of the Google Document.

    Returns:
        str: The content of the Google Doc or an error message if fetching fails.
    """
    export_url = f"https://docs.google.com/document/d/{doc_id}/export?format=txt"
    
    response = requests.get(export_url)
    if response.status_code == 200:
        return response.text
    else:
        return f"Failed to fetch Google Doc. Status code: {response.status_code}"


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

    Args:
        inputs (str): User's input message to the chatbot.
        top_p (float): Top-p (nucleus sampling) parameter for response creativity.
        temperature (float): Temperature for randomness in response.
        chat_counter (int): Number of interactions so far.

    Returns:
        tuple: (response_text, new_chat_counter, updated_chatbot_history)
    """
    global chatbot_history
    
    # 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 chat counter
        chatbot_history,   # Previous conversation history
        api_name="/predict"
    )
    
    # 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 persistent history
    chatbot_history = updated_history

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


if __name__ == "__main__":
    print("Welcome! Let's interact with a Google Doc and GPT-4.")
    
    # Step 1: Ask the user for the Google Docs URL or Document ID
    url_or_id = input("Please provide the Google Docs URL or Document ID: ")
    doc_id = extract_doc_id(url_or_id)

    # Step 2: Fetch the Google Doc content
    print("\nFetching the Google Document content...")
    doc_content = fetch_public_google_doc(doc_id)

    if "Failed to fetch" in doc_content:
        print(doc_content)
    else:
        print("\nGoogle Doc Content fetched successfully!")
        print("--------------------------------------------------")
        print(doc_content[:500])  # Display the first 500 characters for preview
        print("--------------------------------------------------")
        print("The content will be used as context in the chat with GPT-4.")

        # Step 3: Send the document content to GPT-4 to initialize the conversation
        init_prompt = (
            f"The following text is from a Google Document. "
            f"Use this document's content while you're chatting with user:\n\n{doc_content}"
        )
        assistant_reply, chat_counter, chatbot_history = chat_with_model(
            inputs=init_prompt,
            top_p=1.0,
            temperature=0.7,
            chat_counter=0
        )
        print("\nAssistant has analyzed the document and is ready to chat!")
        print(f"Assistant (Initial Reply): {assistant_reply}")

        # Step 4: Allow the user to chat with GPT-4
        chat_counter = 1
        while True:
            user_input = input("\nYou: ")
            if user_input.lower() in ["exit", "quit"]:
                print("Exiting chat. Goodbye!")
                break

            # Chat with GPT-4
            assistant_reply, chat_counter, chatbot_history = chat_with_model(
                inputs=user_input,
                top_p=1.0,
                temperature=0.7,
                chat_counter=chat_counter
            )
            print(f"Assistant: {assistant_reply}")

Also, refer to this code for chat ui
import gradio as gr
from gradio_client import Client

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


def chat_with_model(message, history):
    """
    Interact with the chatbot while maintaining conversation context.
    Args:
        message (str): User's most recent message.
        history (list of dict): Conversation history with 'role' and 'content' keys.
    Returns:
        str: The chatbot's response to the latest user message.
    """
    # Transform history from OpenAI-style dicts to a list of tuples for compatibility
    formatted_history = [(entry["role"], entry["content"]) for entry in history]
    
    if message.strip():  # Avoid empty input
        # Call the Gradio backend Space
        result = client.predict(
            message,             # User message
            1.0,                 # Top-p value for creativity
            0.7,                 # Temperature for randomness
            len(formatted_history),   # Chat counter
            formatted_history,        # Conversation history context
            api_name="/predict"       # API endpoint exposed from Gradio Space
        )

        # Extract updated conversation response (simplify for gr.ChatInterface)
        updated_response = result[0][-1][1]  # Get the chatbot's latest message
        return updated_response
    else:
        return "Please enter a valid message."


# Use gr.ChatInterface for a modern chatbot UI
app = gr.ChatInterface(
    fn=chat_with_model,
    type="messages",  # Ensure compatibility with message history
    title="🤖 ChatGPT-4o",
    description="Interact with GPT-4o without any limitations for free. Type your message below!"
)

# Launch the app
app.launch()