File size: 10,735 Bytes
038f313
77298b9
7de1759
038f313
880ced6
 
e13eb1b
038f313
e13eb1b
038f313
 
 
 
e13eb1b
038f313
 
77298b9
7de1759
 
038f313
 
 
3a64d68
98674ca
77298b9
 
038f313
e13eb1b
52ad57a
7de1759
 
 
 
10ffb1d
 
 
7de1759
 
 
e13eb1b
10ffb1d
7de1759
 
 
 
 
f7c4208
7de1759
52ad57a
 
038f313
7de1759
 
 
 
 
77298b9
e7683ca
77298b9
 
7de1759
 
 
 
 
 
 
77298b9
 
 
 
7de1759
 
77298b9
 
7de1759
77298b9
7de1759
f7c4208
77298b9
7de1759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542c2ac
e13eb1b
f7c4208
7de1759
 
 
77298b9
7de1759
77298b9
7de1759
 
77298b9
7de1759
 
 
e7683ca
8696822
77298b9
7de1759
77298b9
 
 
7de1759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ffb1d
e7683ca
7de1759
 
 
 
e7683ca
10ffb1d
7de1759
 
77298b9
7de1759
 
77298b9
7de1759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77298b9
e7683ca
7de1759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7683ca
7de1759
 
 
 
 
 
 
 
 
e7683ca
7de1759
e7683ca
10ffb1d
7de1759
 
 
10ffb1d
7de1759
 
 
 
 
e7683ca
7de1759
77298b9
7de1759
77298b9
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import gradio as gr
from openai import OpenAI
import os

# Retrieve the access token from the environment variable
ACCESS_TOKEN = os.getenv("HF_TOKEN")
print("Access token loaded.")

# Initialize the OpenAI client with the Hugging Face Inference API endpoint
client = OpenAI(
    base_url="https://api-inference.huggingface.co/v1/",
    api_key=ACCESS_TOKEN,
)
print("OpenAI client initialized.")

def respond(
    user_message,
    chat_history,
    system_msg,
    max_tokens,
    temperature,
    top_p,
    frequency_penalty,
    seed,
    featured_model,
    custom_model
):
    """
    This function handles the chatbot response. It takes in:
    - user_message: the user's newly typed message
    - chat_history: the list of (user, assistant) message pairs
    - system_msg: the system instruction or system-level context
    - max_tokens: the maximum number of tokens to generate
    - temperature: sampling temperature
    - top_p: top-p (nucleus) sampling
    - frequency_penalty: penalize repeated tokens in the output
    - seed: a fixed seed for reproducibility; -1 means 'random'
    - featured_model: the chosen model name from 'Featured Models' radio
    - custom_model: the optional custom model that overrides the featured one if provided
    """

    print(f"Received user message: {user_message}")
    print(f"System message: {system_msg}")
    print(f"Max tokens: {max_tokens}, Temperature: {temperature}, Top-P: {top_p}, Freq-Penalty: {frequency_penalty}, Seed: {seed}")
    print(f"Featured model: {featured_model}")
    print(f"Custom model: {custom_model}")

    # Convert the seed to None if user set it to -1 (meaning random)
    if seed == -1:
        seed = None

    # Decide which model to actually use
    # If custom_model is non-empty, use that; otherwise use the chosen featured_model
    model_to_use = custom_model.strip() if custom_model.strip() != "" else featured_model
    # Provide a default fallback if for some reason both are empty
    if model_to_use.strip() == "":
        model_to_use = "meta-llama/Llama-3.3-70B-Instruct"

    print(f"Model selected for inference: {model_to_use}")

    # Construct the conversation history in the format required by HF's Inference API
    messages = []
    if system_msg.strip():
        messages.append({"role": "system", "content": system_msg.strip()})

    # Add the conversation history
    for user_text, assistant_text in chat_history:
        if user_text:
            messages.append({"role": "user", "content": user_text})
        if assistant_text:
            messages.append({"role": "assistant", "content": assistant_text})

    # Add the new user message to the conversation
    messages.append({"role": "user", "content": user_message})

    # We'll build the response token-by-token in a streaming loop
    response_so_far = ""
    print("Sending request to the Hugging Face Inference API...")

    # Make the streaming request to the HF Inference API
    try:
        for resp_chunk in client.chat.completions.create(
            model=model_to_use,
            max_tokens=max_tokens,
            stream=True,
            temperature=temperature,
            top_p=top_p,
            frequency_penalty=frequency_penalty,
            seed=seed,
            messages=messages,
        ):
            token_text = resp_chunk.choices[0].delta.content
            response_so_far += token_text
            # We yield back the updated message to display partial progress in the chatbot
            yield response_so_far
    except Exception as e:
        # If there's an error, let's at least show it in the chat
        error_text = f"[ERROR] {str(e)}"
        print(error_text)
        yield response_so_far + "\n\n" + error_text

    print("Completed response generation.")

#
# BUILDING THE GRADIO INTERFACE BELOW
#

# List of featured models; adjust or replace these placeholders with real text-generation models
models_list = [
    "meta-llama/Llama-3.3-70B-Instruct",
    "meta-llama/Llama-2-13B-chat-hf",
    "bigscience/bloom",
    "openlm-research/open_llama_7b",
    "facebook/opt-6.7b",
    "google/flan-t5-xxl",
]

def filter_models(search_term):
    """Filters the models_list by the given search_term and returns an update for the Radio component."""
    filtered = [m for m in models_list if search_term.lower() in m.lower()]
    return gr.update(choices=filtered)

with gr.Blocks(theme="Nymbo/Nymbo_Theme_5") as demo:
    gr.Markdown("# Serverless-TextGen-Hub (Enhanced)")
    gr.Markdown("**A comprehensive UI for text generation with a featured-models dropdown and a custom override**.")

    # We keep track of the conversation in a Gradio state variable (list of tuples)
    chat_history = gr.State([])

    # Tabs for organization
    with gr.Tab("Basic Settings"):
        with gr.Row():
            with gr.Column(elem_id="prompt-container"):
                # System Message
                system_msg = gr.Textbox(
                    label="System message",
                    placeholder="Enter system-level instructions or context here.",
                    lines=2
                )
                # Accordion for featured models
                with gr.Accordion("Featured Models", open=True):
                    model_search = gr.Textbox(
                        label="Filter Models",
                        placeholder="Search for a featured model...",
                        lines=1
                    )
                    # The radio that lists our featured models
                    model_radio = gr.Radio(
                        label="Select a featured model below",
                        choices=models_list,
                        value=models_list[0],  # default
                        interactive=True
                    )
                    # Link the search box to update the model_radio choices
                    model_search.change(filter_models, inputs=model_search, outputs=model_radio)

                # Custom Model
                custom_model_box = gr.Textbox(
                    label="Custom Model (Optional)",
                    info="If provided, overrides the featured model above. e.g. 'meta-llama/Llama-3.3-70B-Instruct'",
                    placeholder="Your huggingface.co/username/model_name path"
                )

    with gr.Tab("Advanced Settings"):
        with gr.Row():
            max_tokens_slider = gr.Slider(
                minimum=1,
                maximum=4096,
                value=512,
                step=1,
                label="Max new tokens"
            )
            temperature_slider = gr.Slider(
                minimum=0.1,
                maximum=4.0,
                value=0.7,
                step=0.1,
                label="Temperature"
            )
            top_p_slider = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-P"
            )
        with gr.Row():
            freq_penalty_slider = gr.Slider(
                minimum=-2.0,
                maximum=2.0,
                value=0.0,
                step=0.1,
                label="Frequency Penalty"
            )
            seed_slider = gr.Slider(
                minimum=-1,
                maximum=65535,
                value=-1,
                step=1,
                label="Seed (-1 for random)"
            )

    # Chat interface area: user input -> assistant output
    with gr.Row():
        chatbot = gr.Chatbot(
            label="TextGen Chat",
            height=500
        )

    # The user types a message here
    user_input = gr.Textbox(
        label="Your message",
        placeholder="Type your text prompt here..."
    )

    # "Send" button triggers our respond() function, updates the chatbot
    send_button = gr.Button("Send")

    # A Clear Chat button to reset the conversation
    clear_button = gr.Button("Clear Chat")

    # Define how the Send button updates the state and chatbot
    def user_submission(user_text, history):
        """
        This function gets called first to add the user's message to the chat.
        We return the updated chat_history with the user's message appended,
        plus an empty string for the next user input box.
        """
        if user_text.strip() == "":
            return history, ""
        # Append user message to chat
        history = history + [(user_text, None)]
        return history, ""

    send_button.click(
        fn=user_submission,
        inputs=[user_input, chat_history],
        outputs=[chat_history, user_input]
    )

    # Then we run the respond function (streaming) to generate the assistant message
    def bot_response(
        history,
        system_msg,
        max_tokens,
        temperature,
        top_p,
        freq_penalty,
        seed,
        featured_model,
        custom_model
    ):
        """
        This function is called to generate the assistant's response
        based on the conversation so far, system message, etc. 
        We do the streaming here.
        """
        if not history:
            yield history
        # The last user message is in history[-1][0]
        user_message = history[-1][0] if history else ""
        # We pass everything to respond() generator
        bot_stream = respond(
            user_message=user_message,
            chat_history=history[:-1],  # all except the newly appended user message
            system_msg=system_msg,
            max_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
            frequency_penalty=freq_penalty,
            seed=seed,
            featured_model=featured_model,
            custom_model=custom_model
        )
        partial_text = ""
        for partial_text in bot_stream:
            # We'll keep updating the last message in the conversation with partial_text
            updated_history = history[:-1] + [(history[-1][0], partial_text)]
            yield updated_history

    send_button.click(
        fn=bot_response,
        inputs=[
            chat_history,
            system_msg,
            max_tokens_slider,
            temperature_slider,
            top_p_slider,
            freq_penalty_slider,
            seed_slider,
            model_radio,
            custom_model_box
        ],
        outputs=chatbot
    )

    # Clear chat just resets the state
    def clear_chat():
        return [], ""

    clear_button.click(
        fn=clear_chat,
        inputs=[],
        outputs=[chat_history, user_input]
    )

# Launch the application
if __name__ == "__main__":
    print("Launching the Serverless-TextGen-Hub with Featured Models & Custom Model override.")
    demo.launch()