Spaces:
Running
Running
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() |