File size: 9,117 Bytes
6ebd2d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import gradio as gr
import os
from typing import List, Dict, Optional

# Function to handle chat messages
def chat(message: str, history: List[Dict[str, str]], model_name: str, temperature: float, max_tokens: int) -> List[Dict[str, str]]:
    """
    Generate a response using the Hugging Face Inference API.
    
    Args:
        message: The user's current message
        history: Chat history with previous messages
        model_name: The Hugging Face model to use
        temperature: Sampling temperature for generation
        max_tokens: Maximum tokens to generate
        
    Returns:
        Updated chat history
    """
    try:
        # Build the conversation context
        conversation = []
        
        # Add system message
        conversation.append({
            "role": "system", 
            "content": "You are a helpful, friendly AI assistant. Provide concise, accurate responses."
        })
        
        # Add conversation history
        for user_msg, assistant_msg in history:
            conversation.append({"role": "user", "content": user_msg})
            if assistant_msg:
                conversation.append({"role": "assistant", "content": assistant_msg})
        
        # Add current message
        conversation.append({"role": "user", "content": message})
        
        # Make API call to Hugging Face
        headers = {"Authorization": f"Bearer {os.environ.get('HF_TOKEN', '')}"}
        api_url = f"https://api-inference.huggingface.co/models/{model_name}"
        
        response = requests.post(
            api_url,
            headers=headers,
            json={"inputs": conversation, "parameters": {"temperature": temperature, "max_new_tokens": max_tokens}},
            timeout=60
        )
        
        response.raise_for_status()
        
        # Parse the response
        result = response.json()[0]
        
        # Extract assistant's response
        if isinstance(result, list) and len(result) > 0:
            if isinstance(result[0], list) and len(result[0]) > 0:
                assistant_response = result[0][0].get("generated_text", "")
            else:
                assistant_response = str(result[0])
        else:
            assistant_response = str(result)
        
        # Add assistant response to history
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": assistant_response})
        
        return history
        
    except requests.exceptions.RequestException as e:
        error_msg = f"Error communicating with Hugging Face API: {str(e)}"
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": error_msg})
        return history
    except Exception as e:
        error_msg = f"An unexpected error occurred: {str(e)}"
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": error_msg})
        return history

# Create the Gradio interface
with gr.Blocks(
    title="AI Chatbot",
    description="Chat with various AI models powered by Hugging Face",
    theme=gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="indigo",
        neutral_hue="slate",
        font=gr.themes.GoogleFont("Inter"),
        text_size="lg",
        spacing_size="lg",
        radius_size="md"
    ).set(
        button_primary_background_fill="*primary_600",
        button_primary_background_fill_hover="*primary_700",
        block_title_text_weight="600",
    )
) as demo:
    
    # Header section
    gr.Markdown(
        """
        # ๐Ÿค– AI Chatbot
        Chat with powerful AI models from Hugging Face
        """
    )
    
    # Model selection and settings
    with gr.Accordion("โš™๏ธ Model Settings", open=False):
        with gr.Row():
            with gr.Column():
                model_dropdown = gr.Dropdown(
                    choices=[
                        "mistralai/Mistral-7B-Instruct-v0.2",
                        "meta-llama/Llama-2-7b-chat-hf",
                        "tiiuae/falcon-7b-instruct",
                        "bigscience/bloom-560m",
                        "google/flan-t5-large",
                        "gpt2-xl"
                    ],
                    value="mistralai/Mistral-7B-Instruct-v0.2",
                    label="Select Model",
                    info="Choose an AI model from Hugging Face"
                )
            
            with gr.Column():
                temperature_slider = gr.Slider(
                    minimum=0.0,
                    maximum=1.0,
                    value=0.7,
                    step=0.1,
                    label="Temperature",
                    info="Lower = more focused, Higher = more creative"
                )
            
            with gr.Column():
                max_tokens_slider = gr.Slider(
                    minimum=50,
                    maximum=2048,
                    value=512,
                    step=50,
                    label="Max Tokens",
                    info="Maximum length of response"
                )
    
    # API Token input
    with gr.Row():
        api_token = gr.Textbox(
            label="Hugging Face API Token",
            placeholder="Enter your HF_TOKEN environment variable or paste token here",
            type="password",
            info="Required for private models. Leave empty if using public models."
        )
    
    # Chat interface
    with gr.Row():
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                label="Chat History",
                height=500,
                avatar_images=(
                    "https://api.dicebear.com/7.x/avataaars/svg?seed=AI",
                    "https://api.dicebear.com/7.x/avataaars/svg?seed=User"
                ),
                bubble_full_width=False
            )
        
        with gr.Column(scale=1):
            gr.Markdown(
                """
                ### ๐Ÿ“ Tips
                - Enter your API token for better performance
                - Try different models for different responses
                - Adjust temperature for more creative outputs
                - Clear chat to start fresh
                """
            )
            
            clear_button = gr.Button(
                "๐Ÿ—‘๏ธ Clear Chat",
                variant="secondary",
                size="lg"
            )
    
    # User input
    with gr.Row():
        user_input = gr.Textbox(
            label="Your Message",
            placeholder="Type your message here...",
            scale=4,
            show_label=False
        )
        
        send_button = gr.Button(
            "Send",
            variant="primary",
            scale=1,
            size="lg"
        )
    
    # Example prompts
    gr.Examples(
        examples=[
            ["What is machine learning?"],
            ["Explain quantum computing in simple terms"],
            ["Write a short poem about AI"],
            ["Help me debug this code"],
            ["What are the benefits of renewable energy?"],
            ["Tell me a fun fact about space"],
            ["How do I make a good cup of coffee?"],
            ["What's the difference between Python 2 and 3?"],
        ],
        inputs=user_input,
        label="๐Ÿ’ก Example Prompts"
    )
    
    # Event handlers
    send_button.click(
        fn=chat,
        inputs=[user_input, chatbot, model_dropdown, temperature_slider, max_tokens_slider],
        outputs=[chatbot]
    )
    
    user_input.submit(
        fn=chat,
        inputs=[user_input, chatbot, model_dropdown, temperature_slider, max_tokens_slider],
        outputs=[chatbot]
    )
    
    clear_button.click(
        fn=lambda: [],
        outputs=[chatbot]
    )
    
    # Footer
    gr.Markdown(
        """
        ---
        Built with **[anycoder](https://huggingface.co/spaces/akhaliq/anycoder)**
        """
    )

# Launch the application
if __name__ == "__main__":
    demo.launch(
        theme=gr.themes.Soft(
            primary_hue="blue",
            secondary_hue="indigo",
            neutral_hue="slate",
            font=gr.themes.GoogleFont("Inter"),
            text_size="lg",
            spacing_size="lg",
            radius_size="md"
        ).set(
            button_primary_background_fill="*primary_600",
            button_primary_background_fill_hover="*primary_700",
            block_title_text_weight="600",
        ),
        css="""
        .chatbot-container {
            max-height: 600px !important;
        }
        .chatbot-message {
            margin: 8px 0;
            padding: 12px 16px;
            border-radius: 12px;
            max-width: 80%;
        }
        .chatbot-message.user {
            background-color: #e3f2fd;
            margin-left: auto;
        }
        .chatbot-message.assistant {
            background-color: #f5f5f5;
        }
        """,
        footer_links=[
            {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
        ]
    )