import os import gradio as gr from huggingface_hub import InferenceClient DEFAULT_MODEL = "openai/gpt-oss-20b" DEFAULT_SYSTEM_MESSAGE = "You are a friendly Chatbot." def get_token(hf_token: gr.OAuthToken | None) -> str | None: """Resolve token from Gradio OAuth first, then HF_TOKEN for local runs.""" if hf_token is not None and getattr(hf_token, "token", None): return hf_token.token env_token = os.getenv("HF_TOKEN", "").strip() return env_token or None def _normalize_content(content: object) -> str: """Convert Gradio 6 content blocks or strings into plain text.""" if isinstance(content, str): return content if isinstance(content, list): parts: list[str] = [] for item in content: if isinstance(item, str): parts.append(item) elif isinstance(item, dict) and "text" in item: parts.append(str(item["text"])) return "".join(parts) return str(content) if content is not None else "" def respond( message: str, history: list[dict], system_message: str, max_tokens: int, temperature: float, top_p: float, hf_token: gr.OAuthToken | None = None, ): """ Stream chat completions via Hugging Face InferenceClient. """ token = get_token(hf_token) if not token: yield "🔒 Please log in using the sidebar button (or set `HF_TOKEN` locally)." return if not message or not message.strip(): yield "⚠️ Please enter a message." return messages: list[dict[str, str]] = [] if system_message and system_message.strip(): messages.append({"role": "system", "content": system_message.strip()}) for turn in history or []: if isinstance(turn, dict) and "role" in turn and "content" in turn: role = str(turn["role"]) text = _normalize_content(turn["content"]) if text: messages.append({"role": role, "content": text}) messages.append({"role": "user", "content": message.strip()}) try: client = InferenceClient(token=token, model=DEFAULT_MODEL) response = "" for chunk in client.chat_completion( messages, max_tokens=int(max_tokens), stream=True, temperature=float(temperature), top_p=float(top_p), ): choices = getattr(chunk, "choices", None) if choices and choices[0].delta and choices[0].delta.content: response += choices[0].delta.content yield response except Exception as exc: yield f"❌ **Error:** `{type(exc).__name__}: {exc}`" chatbot = gr.ChatInterface( respond, additional_inputs=[ gr.Textbox(value=DEFAULT_SYSTEM_MESSAGE, 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)", ), ], ) with gr.Blocks() as demo: with gr.Sidebar(): gr.LoginButton() chatbot.render() if __name__ == "__main__": demo.queue(default_concurrency_limit=20).launch()