import gradio as gr from huggingface_hub import InferenceClient import os import time # Fetch the token from the environment variable hf_token = os.getenv("HF_TOKEN") if not hf_token: raise ValueError("HF_TOKEN not found in environment variables. Please set it in Space settings.") # Initialize the Inference API client try: client = InferenceClient(token=hf_token) except Exception as e: raise Exception(f"Failed to initialize InferenceClient: {str(e)}") # Chat function with retry logic def chat_with_bot(user_input, history=[]): max_retries = 3 for attempt in range(max_retries): try: response = client.text_generation( prompt=user_input, model="microsoft/DialoGPT-large" ) history.append([user_input, response]) chat_output = "\n".join([f"You: {h[0]}\nBot: {h[1]}" for h in history]) return chat_output, history except Exception as e: if attempt < max_retries - 1: time.sleep(1) # Shorter delay for faster retries continue return f"Chat Error: {str(e)} (after {max_retries} attempts)", history # Test the API def test_api(): max_retries = 3 for attempt in range(max_retries): try: response = client.text_generation( prompt="Hi", model="microsoft/DialoGPT-large" ) return response except Exception as e: if attempt < max_retries - 1: time.sleep(1) continue return f"API Test Error: {str(e)} (after {max_retries} attempts)" # Create Gradio interface interface = gr.Interface( fn=chat_with_bot, inputs=["text", "state"], outputs=["text", "state"], title="My DialoGPT Chatbot", description=f"Powered by Microsoft DialoGPT Large | API Test: {test_api()}" ) # Launch the app interface.launch()