Spaces:
Running on Zero

MeloonHub2 / api_examples.py
isold's picture
Ship the API examples and the local vision-path verifier
5d7ffac
Raw History Blame Contribute Delete
7.74 kB
"""MeloonHub2 (Qwen3.8-27B) 的三种调用方式。
Space: https://isold23-meloonhub2.hf.space
接口: /respond —— 参数与默认值来自线上 /gradio_api/info 的实测结果:
message dict {"text": str, "files": list[filepath]} 默认 {"text":"","files":[]}
system_prompt str 默认 ""
reasoning str "off" | "low" | "medium" | "xhigh" 默认 "off"
temperature float 默认 0.7
top_p float 默认 0.8
top_k float 默认 20
max_new_tokens float 默认 1024
返回: list[dict],每个元素是一条 ChatMessage:
{"role": "assistant", "content": "...", "metadata": {"title": "Reasoning"}}
思考模式下推理过程会单独成为一条 title="Reasoning" 的消息。
注意: ChatInterface 的 API 签名里 **没有 history 参数**(历史存在服务端 session 里)。
运行:
pip install gradio_client
python api_examples.py # 跑一遍三种方式
python api_examples.py "你好" /tmp/a.png
"""
from __future__ import annotations
import json
import sys
import urllib.request
BASE = "https://isold23-meloonhub2.hf.space"
ENDPOINT = "/respond"
# ZeroGPU 额度按访客账号算: 未登录 2 分钟/天, 免费 5 分钟, PRO 40 分钟,
# 且按「预约时长」扣费而不是实际耗时。传自己的 token 可以把额度算到自己头上。
# 不要硬编码 token —— 用环境变量 HF_TOKEN, 或先执行 `hf auth login`。
HF_TOKEN = None # 例如 os.environ.get("HF_TOKEN")
# --------------------------------------------------------------------------
# 方式一: gradio_client(推荐, 最省事, 自动处理上传和 SSE)
# --------------------------------------------------------------------------
def call_with_gradio_client(text: str, files: list[str] | None = None, **kw):
"""files 里放本地路径即可 —— 但必须用 handle_file() 包一层。
直接传路径字符串会被 Gradio 的 FileData 校验拒掉, 报错是毫无信息量的
"the Gradio app has raised an exception", 极容易误判成服务端 bug。
"""
from gradio_client import Client, handle_file
client = Client(BASE, hf_token=HF_TOKEN, verbose=False)
return client.predict(
{"text": text, "files": [handle_file(f) for f in (files or [])]},
kw.get("system_prompt", ""),
kw.get("reasoning", "off"),
kw.get("temperature", 0.7),
kw.get("top_p", 0.80),
kw.get("top_k", 20),
kw.get("max_new_tokens", 256),
api_name=ENDPOINT,
)
# --------------------------------------------------------------------------
# 方式二: 原生 HTTP(只用标准库, 两步式: POST 拿 event_id -> GET 收 SSE)
# --------------------------------------------------------------------------
def _iter_sse(resp):
"""把 SSE 响应体解析成 (event_name, data_str) 序列。
注意 Gradio 用 CRLF 行尾 —— 只 rstrip("\\n") 会留下 \\r, 空行判断就永远不成立,
整个流一条事件都读不出来(静默返回空列表, 很难查)。
"""
event, data = None, []
for raw in resp:
line = raw.decode("utf-8").rstrip("\r\n")
if line.startswith("event:"):
event = line[6:].strip()
elif line.startswith("data:"):
data.append(line[5:].strip())
elif not line and (event or data):
yield event, "\n".join(data)
event, data = None, []
if event or data: # 结尾没有空行时兜住最后一条
yield event, "\n".join(data)
def _sse_events(url: str):
req = urllib.request.Request(url)
if HF_TOKEN:
req.add_header("Authorization", f"Bearer {HF_TOKEN}")
with urllib.request.urlopen(req, timeout=600) as resp:
yield from _iter_sse(resp)
def call_with_raw_http(text: str, **kw):
"""不装 gradio_client 也能调。附件需要先 POST /gradio_api/upload 拿路径。"""
payload = {
"data": [
{"text": text, "files": []},
kw.get("system_prompt", ""),
kw.get("reasoning", "off"),
kw.get("temperature", 0.7),
kw.get("top_p", 0.80),
kw.get("top_k", 20),
kw.get("max_new_tokens", 256),
]
}
# 提交任务
req = urllib.request.Request(
BASE + "/gradio_api/call/v2" + ENDPOINT,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
if HF_TOKEN:
req.add_header("Authorization", f"Bearer {HF_TOKEN}")
with urllib.request.urlopen(req, timeout=60) as resp:
event_id = json.load(resp)["event_id"]
# 收结果。流式生成会发多次 process_generating, 最后一次是 complete。
final = None
for name, data in _sse_events(f"{BASE}/gradio_api/call{ENDPOINT}/{event_id}"):
if name == "error":
raise RuntimeError(f"服务端返回错误: {data}")
try:
body = json.loads(data)
except json.JSONDecodeError:
continue
if name == "complete":
final = body
elif isinstance(body, dict) and body.get("msg") == "process_completed":
final = body.get("output", {}).get("data")
return final
# --------------------------------------------------------------------------
# 方式三: MCP(给 Agent / LLM 当工具用, 服务端已开启 mcp_server=True)
# --------------------------------------------------------------------------
MCP_URL = BASE + "/gradio_api/mcp/"
# 实测 tools/list 返回一个工具: MeloonHub2_respond
#
# 客户端配置(Claude Desktop / 支持 MCP 的客户端):
# {
# "mcpServers": {
# "meloonhub2": {
# "url": "https://isold23-meloonhub2.hf.space/gradio_api/mcp/",
# "headers": {"Authorization": "Bearer <你的 HF token>"}
# }
# }
# }
def call_mcp_tools_list():
"""裸 JSON-RPC 探一下 MCP 服务端暴露了哪些工具。"""
req = urllib.request.Request(
MCP_URL,
data=json.dumps(
{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}
).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
},
)
with urllib.request.urlopen(req, timeout=60) as resp:
for name, data in _iter_sse(resp):
if name == "message":
return json.loads(data)["result"]["tools"]
return []
# --------------------------------------------------------------------------
def show(label: str, result) -> None:
print(f"\n===== {label} =====")
if isinstance(result, str):
print(result[:600])
return
if not isinstance(result, list):
print(repr(result)[:600])
return
for item in result:
if isinstance(item, dict) and "role" in item:
title = (item.get("metadata") or {}).get("title")
tag = f" [{title}]" if title else ""
print(f"-- {item['role']}{tag}")
print(" ", str(item.get("content"))[:500].replace("\n", "\n "))
if __name__ == "__main__":
prompt = sys.argv[1] if len(sys.argv) > 1 else "用一句话说明什么是 ZeroGPU。"
attach = sys.argv[2:] if len(sys.argv) > 2 else None
print("MCP 工具列表:", [t["name"] for t in call_mcp_tools_list()])
show("方式一 gradio_client", call_with_gradio_client(prompt, attach))
show("方式二 原生 HTTP", call_with_raw_http(prompt))