Spaces:
Running on Zero

File size: 7,739 Bytes
5d7ffac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""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))