import os import gradio as gr from huggingface_hub import InferenceClient # 1. Define the list of available models # You can add any model ID from Hugging Face that supports the Inference API 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, # 2. Accept model_id as an argument ): # Load the token from the environment variable "HF_TOKEN" token = os.getenv("HF_TOKEN") # Check if token exists (Optional safety check) if not token: yield "Error: HF_TOKEN environment variable is not set. Please set it in your terminal." return # 3. Initialize the client with the USER-SELECTED model client = InferenceClient(token=token, model=model_id) messages = [{"role": "system", "content": system_message}] # History format: [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}] 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)", ), # 4. Add the Dropdown for Model Selection gr.Dropdown( choices=MODELS, value=MODELS[0], # Default model label="Select Model", interactive=True ), ], ) # Clean Layout without Sidebar/Login with gr.Blocks(fill_height=True) as demo: chatbot.render() if __name__ == "__main__": demo.launch()