|
|
import os |
|
|
import gradio as gr |
|
|
from huggingface_hub import InferenceClient |
|
|
|
|
|
|
|
|
|
|
|
MODELS = [ |
|
|
"baidu/ERNIE-4.5-21B-A3B-PT", |
|
|
"moonshotai/Kimi-K2-Thinking", |
|
|
"meta-llama/Meta-Llama-3-8B-Instruct", |
|
|
"openai/gpt-oss-20b", |
|
|
"openai/gpt-oss-120b", |
|
|
] |
|
|
|
|
|
def respond( |
|
|
message, |
|
|
history: list[dict[str, str]], |
|
|
system_message, |
|
|
max_tokens, |
|
|
temperature, |
|
|
top_p, |
|
|
model_id, |
|
|
): |
|
|
|
|
|
token = os.getenv("HF_TOKEN") |
|
|
|
|
|
|
|
|
if not token: |
|
|
yield "Error: HF_TOKEN environment variable is not set. Please set it in your terminal." |
|
|
return |
|
|
|
|
|
|
|
|
client = InferenceClient(token=token, model=model_id) |
|
|
|
|
|
messages = [{"role": "system", "content": system_message}] |
|
|
|
|
|
|
|
|
messages.extend(history) |
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
|
|
response = "" |
|
|
|
|
|
try: |
|
|
for message in client.chat_completion( |
|
|
messages, |
|
|
max_tokens=max_tokens, |
|
|
stream=True, |
|
|
temperature=temperature, |
|
|
top_p=top_p, |
|
|
): |
|
|
choices = message.choices |
|
|
token = "" |
|
|
if len(choices) and choices[0].delta.content: |
|
|
token = choices[0].delta.content |
|
|
|
|
|
response += token |
|
|
yield response |
|
|
except Exception as e: |
|
|
yield f"API Error for model {model_id}: {str(e)}" |
|
|
|
|
|
""" |
|
|
ChatInterface Configuration |
|
|
""" |
|
|
chatbot = gr.ChatInterface( |
|
|
respond, |
|
|
type="messages", |
|
|
fill_height=True, |
|
|
additional_inputs=[ |
|
|
gr.Textbox(value="You are a friendly Chatbot.", label="System message"), |
|
|
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), |
|
|
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), |
|
|
gr.Slider( |
|
|
minimum=0.1, |
|
|
maximum=1.0, |
|
|
value=0.95, |
|
|
step=0.05, |
|
|
label="Top-p (nucleus sampling)", |
|
|
), |
|
|
|
|
|
gr.Dropdown( |
|
|
choices=MODELS, |
|
|
value=MODELS[0], |
|
|
label="Select Model", |
|
|
interactive=True |
|
|
), |
|
|
], |
|
|
) |
|
|
|
|
|
|
|
|
with gr.Blocks(fill_height=True) as demo: |
|
|
chatbot.render() |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |