File size: 3,369 Bytes
d14a5d3
60c9157
 
 
db8e0c1
 
d14a5d3
 
db8e0c1
 
d14a5d3
 
 
 
 
60c9157
dc4bffb
db8e0c1
dc4bffb
 
 
 
 
 
 
 
 
 
 
 
 
60c9157
d14a5d3
 
 
 
 
 
 
60c9157
db8e0c1
 
 
 
d14a5d3
db8e0c1
d14a5d3
60c9157
d14a5d3
 
 
60c9157
d14a5d3
 
 
60c9157
d14a5d3
 
dc4bffb
 
 
 
60c9157
d14a5d3
60c9157
d14a5d3
db8e0c1
d14a5d3
60c9157
d14a5d3
db8e0c1
d14a5d3
 
 
 
 
 
 
 
 
 
 
db8e0c1
60c9157
 
 
db8e0c1
60c9157
db8e0c1
 
 
 
 
 
 
 
 
dc4bffb
60c9157
 
 
db8e0c1
60c9157
 
 
 
 
d14a5d3
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
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()