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.
code
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.
code
Assistant
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.")
code
# 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]
code
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()
To convert your initial Python script into a Gradio web-based user interface (UI) with integration of functionalities like fetching the Google Doc content, and maintaining conversation history with the gr.ChatInterface, we can create a new Gradio interface. Here’s how we can structure it:
python
import gradio as gr
import requests
from gradio_client import Client
# GPT-4 API Client Initialization
client = Client("yuntian-deng/ChatGPT4")
# Persistent conversation history
chatbot_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
def fetch_public_google_doc(doc_id):
"""
Fetch the content of a public Google Doc using its Document ID.
"""
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(message, history, doc_content):
"""
Handle chat with GPT-4 model maintaining memory and integrating Google Doc content.
"""
global chatbot_history
init_prompt = ("The following text is from a Google Document that the user provided. "
"Use this content as context while chatting:\n\n" + doc_content)
# If history is empty, initialize with the document content
if len(history) == 0:
chatbot_history.append(("user", init_prompt))
# Update the chat history for the current message
chatbot_history.append(("user", message))
# Call GPT-4 via Gradio API client
result = client.predict(
message, # Current user message
1.0, # Top-p value
0.7, # Temperature
len(chatbot_history), # Number of interactions
chatbot_history, # Current chatbot history
api_name="/predict"
)
# Get the latest response
reply = result[0][-1][1] # Bot's last message
chatbot_history.append(("assistant", reply)) # Update chatbot history
return reply
# Define the Gradio Interface
def interface_fn(url_or_id, message, conversation_history):
"""
Unified Gradio interface function to handle user input.
"""
# Extract Google Doc ID
doc_id = extract_doc_id(url_or_id)
# Fetch Google Doc content
doc_content = fetch_public_google_doc(doc_id)
if "Failed to fetch" in doc_content:
return {"response": doc_content, "chat_history": conversation_history}
# Chat with the model
response = chat_with_model(message, conversation_history, doc_content)
conversation_history.append({"role": "user", "content": message})
conversation_history.append({"role": "assistant", "content": response})
return {"response": response, "chat_history": conversation_history}
# Use gr.ChatInterface for a chatbot-style UI
with gr.Blocks() as app:
gr.Markdown("<h1>🌟 Chat with GPT-4 & Google Doc Integration</h1>")
doc_input = gr.Textbox(
label="Google Doc URL or Doc ID",
placeholder="Paste the Google Doc URL or Document ID here"
)
chatbot = gr.Chatbot()
msg_input = gr.Textbox(
label="Your Message",
placeholder="Type your message here and press Enter"
)
def handle_input(url_or_id, message, chat_history):
result = interface_fn(url_or_id, message, chat_history)
return result["chat_history"], ""
chat_history = gr.State([]) # Maintain the chat history
# Bind user actions to the chatbot
msg_input.submit(handle_input,
inputs=[doc_input, msg_input, chat_history],
outputs=[chatbot, msg_input])
gr.Markdown("## Instructions: \n1. Provide your public Google Doc URL or Document ID. \n"
"2. Start chatting about the document!")
# Launch the app
app.launch()
Key Features of the Gradio UI:
Input for Google Doc URL/ID: Users can provide the URL or ID.
Integrated Chatbot: A gr.Chatbot component allows interaction with GPT-4 while maintaining the context of the Google Document.
State Preservation: The gr.State component ensures the persistent storage of conversation history across multiple interactions.
Workflow:
The user enters the Google Doc URL or ID.
The system fetches the content of the Google Doc.
The user interacts with GPT-4, and each response leverages the content of the Google Doc for context.
Notes:
The gr.ChatInterface or a combination of gr.Blocks ensures a visually appealing UI.
gr.Textbox handles user inputs for Doc URLs and chat messages.
gr.State manages backend state like conversation history.
To Run:
Save the code in a Python file and execute it. Ensure Gradio and Gradio Client are installed (pip install gradio gradio-client), and make sure the GPT-4 endpoint is accessible.