Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Small Gradio chat for Hugging Face Spaces.
|
| 3 |
+
Uses the Serverless Inference API; HF_TOKEN is injected automatically on Spaces.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
from huggingface_hub import InferenceClient
|
| 13 |
+
|
| 14 |
+
# Small instruct model (change via Space variable CHAT_MODEL or edit here)
|
| 15 |
+
MODEL_ID = os.environ.get("CHAT_MODEL", "meta-llama/Llama-3.2-1B-Instruct")
|
| 16 |
+
MAX_TOKENS = int(os.environ.get("CHAT_MAX_TOKENS", "512"))
|
| 17 |
+
|
| 18 |
+
_client: InferenceClient | None = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _get_client() -> InferenceClient:
|
| 22 |
+
global _client
|
| 23 |
+
if _client is None:
|
| 24 |
+
_client = InferenceClient()
|
| 25 |
+
return _client
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _content_to_str(content: Any) -> str:
|
| 29 |
+
if isinstance(content, str):
|
| 30 |
+
return content
|
| 31 |
+
if isinstance(content, list):
|
| 32 |
+
parts: list[str] = []
|
| 33 |
+
for item in content:
|
| 34 |
+
if isinstance(item, str):
|
| 35 |
+
parts.append(item)
|
| 36 |
+
elif isinstance(item, dict) and "path" in item:
|
| 37 |
+
parts.append(f"[file: {item['path']}]")
|
| 38 |
+
else:
|
| 39 |
+
parts.append(str(item))
|
| 40 |
+
return "\n".join(parts)
|
| 41 |
+
return str(content)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def respond(message: str, history: list[dict[str, Any]]) -> str:
|
| 45 |
+
"""Gradio 6+ passes prior turns as OpenAI-style dicts; `message` is the new user text."""
|
| 46 |
+
if not (message or "").strip():
|
| 47 |
+
return ""
|
| 48 |
+
|
| 49 |
+
# Omit `system` role: some serverless chat models reject it on the Inference API.
|
| 50 |
+
messages: list[dict[str, str]] = []
|
| 51 |
+
for msg in history:
|
| 52 |
+
role = msg.get("role")
|
| 53 |
+
if role not in ("user", "assistant"):
|
| 54 |
+
continue
|
| 55 |
+
text = _content_to_str(msg.get("content"))
|
| 56 |
+
if text.strip():
|
| 57 |
+
messages.append({"role": role, "content": text})
|
| 58 |
+
messages.append({"role": "user", "content": message})
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
out = _get_client().chat_completion(
|
| 62 |
+
model=MODEL_ID,
|
| 63 |
+
messages=messages,
|
| 64 |
+
max_tokens=MAX_TOKENS,
|
| 65 |
+
)
|
| 66 |
+
choice = out.choices[0]
|
| 67 |
+
msg = choice.message
|
| 68 |
+
text = getattr(msg, "content", None) or (msg.get("content") if isinstance(msg, dict) else None)
|
| 69 |
+
return (text or "").strip() or "(empty reply)"
|
| 70 |
+
except Exception as exc: # noqa: BLE001 — show user-visible fallback
|
| 71 |
+
return (
|
| 72 |
+
f"**Could not reach the model** (`{MODEL_ID}`).\n\n"
|
| 73 |
+
f"Details: `{exc!s}`\n\n"
|
| 74 |
+
"On a **local** run, set `HF_TOKEN` or run `hf auth login`. "
|
| 75 |
+
"On **Spaces**, enable a token with Inference access in Space secrets if needed.\n\n"
|
| 76 |
+
f"---\n*Echo:* {message}"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
demo = gr.ChatInterface(
|
| 81 |
+
fn=respond,
|
| 82 |
+
title="Small Chat",
|
| 83 |
+
description=f"Chat via [Hugging Face Inference](https://huggingface.co/docs/api-inference/index). Model: `{MODEL_ID}`.",
|
| 84 |
+
examples=["What is 2+2?", "Explain recursion in one sentence."],
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
demo.launch()
|