Dellboy commited on
Commit
af2889b
·
verified ·
1 Parent(s): 36d987d

Publish /chat via explicit components: gr.api discarded every token

Browse files
Files changed (1) hide show
  1. test_api_contract.py +101 -0
test_api_contract.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assert the Space publishes the API contract chatmcd/hf_client.py calls.
2
+
3
+ This is the test that did not exist while two contract bugs shipped, each of
4
+ which returned an empty answer with no error and cost a Space rebuild to find:
5
+
6
+ * six arguments sent to a five-parameter endpoint (history -> temperature)
7
+ * an endpoint published with `returns: []`, which ran the generator on a GPU
8
+ and threw every token away
9
+
10
+ Both are visible in the published schema, so this reads the schema. It builds
11
+ the real ui.build_demo with a stub generator in place of Qwen3-8B, launches it
12
+ on a local port, and calls it exactly as the Flask app does.
13
+
14
+ .venv-gradio/bin/python3 -m pytest space/test_api_contract.py -q
15
+
16
+ Needs a Python with gradio installed; the project venv is 3.14 and gradio's
17
+ pydantic pin has no wheel for it, hence the separate .venv-gradio (3.12).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ import pytest
26
+
27
+ sys.path.insert(0, str(Path(__file__).parent))
28
+
29
+ from ui import CHAT_API_PARAMS, build_demo # noqa: E402
30
+
31
+ STUB_TOKENS = ["Nottingham ", "Forest", ", and he has since 1979."]
32
+
33
+
34
+ def stub_chat(message, history=None, temperature=0.7, top_p=0.9,
35
+ repetition_penalty=1.05, max_new_tokens=512):
36
+ """Stands in for the real generator: same shape, no model.
37
+
38
+ Echoes the arguments it received so a silently shifted parameter shows up as
39
+ a wrong value rather than as a plausible answer.
40
+ """
41
+ yield f"[h={0 if not history else len(history)} t={temperature} " \
42
+ f"p={top_p} r={repetition_penalty} n={int(max_new_tokens)}] "
43
+ out = ""
44
+ for tok in STUB_TOKENS:
45
+ out += tok
46
+ yield f"[h={0 if not history else len(history)} t={temperature} " \
47
+ f"p={top_p} r={repetition_penalty} n={int(max_new_tokens)}] {out}"
48
+
49
+
50
+ @pytest.fixture(scope="module")
51
+ def client():
52
+ from gradio_client import Client
53
+
54
+ demo = build_demo(stub_chat, base_model="stub", adapter="", retrieval_on=True)
55
+ demo.queue(max_size=4).launch(prevent_thread_lock=True, quiet=True,
56
+ share=False, ssr_mode=False)
57
+ try:
58
+ yield Client(demo.local_url, verbose=False)
59
+ finally:
60
+ demo.close()
61
+
62
+
63
+ def endpoint(client, name):
64
+ info = client.view_api(return_format="dict", print_info=False)
65
+ named = info["named_endpoints"]
66
+ assert name in named, f"{name} is not published; have {sorted(named)}"
67
+ return named[name]
68
+
69
+
70
+ def test_chat_takes_the_six_arguments_flask_sends(client):
71
+ """hf_client.py submits six positionals. The endpoint must accept six."""
72
+ params = [p["parameter_name"] for p in endpoint(client, "/chat")["parameters"]]
73
+ assert tuple(params) == CHAT_API_PARAMS
74
+
75
+
76
+ def test_chat_declares_an_output(client):
77
+ """`returns: []` is the bug that ran the GPU and discarded the answer."""
78
+ assert endpoint(client, "/chat")["returns"], \
79
+ "/chat publishes no outputs: every call will return an empty tuple"
80
+
81
+
82
+ def test_chat_streams_and_returns_the_answer(client):
83
+ """submit() must yield partials, and the last one must be the full answer."""
84
+ job = client.submit("Which football team does Marc support?", None,
85
+ 0.7, 0.9, 1.05, 256, api_name="/chat")
86
+ partials = [p if isinstance(p, str) else str(p) for p in job]
87
+ assert partials, "the endpoint yielded nothing"
88
+ assert "".join(STUB_TOKENS) in partials[-1]
89
+
90
+
91
+ def test_arguments_are_not_shifted(client):
92
+ """The stub echoes what it got. Non-default values must arrive intact."""
93
+ answer = client.predict("hello", [{"role": "user", "content": "hi"}],
94
+ 0.11, 0.22, 1.33, 128, api_name="/chat")
95
+ text = answer if isinstance(answer, str) else str(answer)
96
+ assert "h=1 t=0.11 p=0.22 r=1.33 n=128" in text, text[:200]
97
+
98
+
99
+ def test_chat_ui_is_still_published(client):
100
+ """The debug UI's own endpoint, which must not collide with /chat."""
101
+ assert endpoint(client, "/chat_ui")["parameters"]