File size: 1,950 Bytes
960bc52
 
926bd72
0578586
960bc52
926bd72
 
d907861
 
926bd72
d907861
 
 
 
 
a790652
0578586
a790652
0578586
 
 
 
 
fde9ffa
0578586
 
 
 
 
 
e522eda
0578586
 
d907861
 
 
0578586
 
 
 
 
84ce09d
0578586
 
 
 
e522eda
0578586
 
a790652
 
 
 
 
 
e522eda
fde9ffa
960bc52
 
a790652
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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()