File size: 12,914 Bytes
48dbacb
 
 
 
 
de12842
48dbacb
 
 
de12842
 
48dbacb
 
 
a19f717
48dbacb
 
a19f717
48dbacb
 
 
 
 
a0cc9e0
48dbacb
 
 
 
 
de12842
a0cc9e0
48dbacb
 
 
a0cc9e0
 
 
 
48dbacb
a0cc9e0
 
48dbacb
59bdabf
de12842
48dbacb
 
 
a0cc9e0
48dbacb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0cc9e0
48dbacb
 
 
a0cc9e0
48dbacb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0cc9e0
 
48dbacb
 
 
 
a0cc9e0
48dbacb
 
a0cc9e0
 
48dbacb
 
 
 
a0cc9e0
 
48dbacb
 
 
a0cc9e0
48dbacb
 
 
 
 
 
 
a0cc9e0
 
48dbacb
 
 
 
 
 
 
 
 
 
 
e361d46
48dbacb
 
 
 
 
 
 
 
 
 
 
 
a0cc9e0
48dbacb
 
 
 
de12842
 
48dbacb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de12842
48dbacb
de12842
48dbacb
 
 
 
 
 
 
a0cc9e0
 
48dbacb
a0cc9e0
 
48dbacb
 
 
a0cc9e0
48dbacb
 
 
 
 
 
 
 
a0cc9e0
48dbacb
 
 
 
 
970a5a0
48dbacb
970a5a0
48dbacb
 
 
 
 
 
 
 
970a5a0
48dbacb
 
a0cc9e0
 
48dbacb
 
 
a0cc9e0
48dbacb
 
 
a0cc9e0
48dbacb
 
 
a0cc9e0
48dbacb
 
 
 
 
 
 
a0cc9e0
48dbacb
970a5a0
 
48dbacb
 
 
 
 
 
 
 
970a5a0
48dbacb
 
970a5a0
48dbacb
 
 
970a5a0
48dbacb
a0cc9e0
 
48dbacb
 
 
 
a0cc9e0
 
48dbacb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import os
import uuid
from enum import Enum
from html import escape
from typing import Optional

from fastapi import FastAPI, Form, Header, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel


# =============================================================================
# Configuration
# =============================================================================

BROKER_TOKEN = os.environ.get("BROKER_TOKEN")
UI_TOKEN = os.environ.get("UI_TOKEN")

if not BROKER_TOKEN:
    raise RuntimeError(
        "Missing BROKER_TOKEN. Add it in Hugging Face Space "
        "Settings → Variables and secrets → New secret."
    )

if not UI_TOKEN:
    raise RuntimeError(
        "Missing UI_TOKEN. Add it in Hugging Face Space "
        "Settings → Variables and secrets → New secret."
    )


# =============================================================================
# Safe predefined options
# =============================================================================

MODEL_OPTIONS = {
    "granite-4.1-8b": "ibm-granite/granite-4.1-8b",
    "granite-4.1-30b": "ibm-granite/granite-4.1-30b",
    "llama-3-3-70b-instruct": "meta-llama/llama-3-3-70b-instruct",
}

QUERY_LLM_COMMAND = "query_llm"


# =============================================================================
# Data model
# =============================================================================

class JobStatus(str, Enum):
    queued = "queued"
    running = "running"
    done = "done"
    failed = "failed"


class Job(BaseModel):
    id: str
    command: str
    status: JobStatus = JobStatus.queued
    result: Optional[str] = None

    # Parameters for query_llm
    model: Optional[str] = None
    gpus: Optional[int] = None
    user_text: Optional[str] = None


app = FastAPI(title="Fury Broker")

# In-memory storage. Jobs disappear if the Space restarts.
jobs: dict[str, Job] = {}


# =============================================================================
# Security helpers
# =============================================================================

def verify_broker_token(x_broker_token: Optional[str]) -> None:
    """
    Used by the Fury worker and command-line API calls.

    Header:
        X-Broker-Token: BROKER_TOKEN
    """
    if x_broker_token != BROKER_TOKEN:
        raise HTTPException(status_code=401, detail="Unauthorized")


def verify_ui_token(ui_token: Optional[str]) -> None:
    """
    Used by browser form submissions.

    Form field:
        ui_token
    """
    if ui_token != UI_TOKEN:
        raise HTTPException(status_code=401, detail="Invalid UI token")



def validate_query_llm_args(
    model: str,
    gpus: int,
    user_text: str,
) -> None:
    if model not in MODEL_OPTIONS:
        raise HTTPException(status_code=400, detail=f"Model is not allowed: {model}")

    if gpus < 1 or gpus > 16:
        raise HTTPException(status_code=400, detail="GPUs must be between 1 and 16")

    if user_text is None:
        raise HTTPException(status_code=400, detail="Prompt is required")

    if len(user_text.strip()) == 0:
        raise HTTPException(status_code=400, detail="Prompt cannot be empty")

    if len(user_text) > 10_000:
        raise HTTPException(
            status_code=400,
            detail="Prompt is too long; max 10,000 characters",
        )


# =============================================================================
# Health and inspection APIs
# =============================================================================

@app.get("/health")
def health():
    return {
        "status": "ok",
        "service": "fury-broker",
        "jobs_count": len(jobs),
    }


@app.get("/api/commands")
def list_commands(x_broker_token: Optional[str] = Header(default=None)):
    verify_broker_token(x_broker_token)

    return {
        "query_llm": {
            "command": QUERY_LLM_COMMAND,
            "model_options": MODEL_OPTIONS,
            "gpu_range": [1, 16],
            "default_gpus": 1,
            "default_prompt": "hello",
        },
    }


# =============================================================================
# Browser UI
# =============================================================================

@app.get("/", response_class=HTMLResponse)
def home():
    model_options_html = "\n".join(
        f'<option value="{escape(key)}">{escape(value)}</option>'
        for key, value in MODEL_OPTIONS.items()
    )

    gpu_options_html = "\n".join(
        f'<option value="{i}" {"selected" if i == 1 else ""}>{i}</option>'
        for i in range(1, 17)
    )

    rows = ""

    for job in reversed(list(jobs.values())):
        details = []

        if job.model:
            details.append(f"model={job.model}")

        if job.gpus:
            details.append(f"gpus={job.gpus}")

        if job.user_text:
            preview = job.user_text[:500]
            if len(job.user_text) > 500:
                preview += "..."
            details.append(f"prompt={preview}")

        safe_details = escape("\n".join(details))
        safe_result = escape(job.result or "")

        rows += f"""
        <tr>
            <td><code>{escape(job.id)}</code></td>
            <td>{escape(job.command)}</td>
            <td>{escape(job.status.value)}</td>
            <td><pre>{safe_details}</pre></td>
            <td><pre>{safe_result}</pre></td>
        </tr>
        """

    return f"""
    <!doctype html>
    <html>
        <head>
            <title>Fury Broker</title>
            <style>
                body {{
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
                    margin: 40px;
                    max-width: 1300px;
                    line-height: 1.45;
                }}
                h1 {{
                    margin-bottom: 0.2rem;
                }}
                .subtitle {{
                    color: #555;
                    margin-bottom: 2rem;
                }}
                form {{
                    margin: 1.5rem 0;
                    padding: 1rem;
                    border: 1px solid #ddd;
                    border-radius: 8px;
                    background: #fafafa;
                }}
                input, select, textarea, button {{
                    padding: 6px;
                    margin: 4px;
                }}
                textarea {{
                    width: 95%;
                    font-family: monospace;
                }}
                table {{
                    border-collapse: collapse;
                    width: 100%;
                    margin-top: 20px;
                }}
                th, td {{
                    border: 1px solid #ccc;
                    padding: 8px;
                    vertical-align: top;
                }}
                th {{
                    background: #f5f5f5;
                    text-align: left;
                }}
                pre {{
                    white-space: pre-wrap;
                    max-width: 600px;
                    max-height: 500px;
                    overflow: auto;
                    margin: 0;
                }}
                .warning {{
                    color: #8a4b00;
                    background: #fff4dd;
                    border: 1px solid #f0c36d;
                    padding: 0.8rem;
                    border-radius: 6px;
                }}
            </style>
        </head>
        <body>
            <h1>Fury Broker</h1>
            <div class="subtitle">
                Submit approved jobs from Hugging Face Spaces to the worker running on Fury.
            </div>

            <div class="warning">
                This UI submits only validated query_llm jobs.
                Fury validates the model, GPU count, and prompt again locally before execution.
            </div>

            <form method="post" action="/submit-query-llm">
                <h2>query_llm</h2>

                <div>
                    <label><strong>UI token:</strong></label>
                    <input type="password" name="ui_token" placeholder="Enter UI_TOKEN" required>
                </div>

                <div>
                    <label><strong>Model:</strong></label>
                    <select name="model">
                        {model_options_html}
                    </select>
                </div>

                <div>
                    <label><strong>Number of GPUs:</strong></label>
                    <select name="gpus">
                        {gpu_options_html}
                    </select>
                </div>

                <div>
                    <label><strong>Prompt to send to the LLM:</strong></label><br>
                    <textarea
                        name="user_text"
                        rows="8"
                        required
                    >hello</textarea>
                </div>

                <button type="submit">Submit query_llm job</button>
            </form>

            <p>
                Refresh the page after a few seconds to see updated results.
            </p>

            <h2>Jobs</h2>

            <table>
                <tr>
                    <th>ID</th>
                    <th>Command</th>
                    <th>Status</th>
                    <th>Parameters</th>
                    <th>Result</th>
                </tr>
                {rows}
            </table>
        </body>
    </html>
    """


# =============================================================================
# Browser submit endpoints
# =============================================================================

@app.post("/submit-query-llm")
def submit_query_llm_from_ui(
    model: str = Form(...),
    gpus: int = Form(1),
    user_text: str = Form("hello"),
    ui_token: str = Form(...),
):
    verify_ui_token(ui_token)

    validate_query_llm_args(
        model=model,
        gpus=gpus,
        user_text=user_text,
    )

    job_id = str(uuid.uuid4())

    jobs[job_id] = Job(
        id=job_id,
        command=QUERY_LLM_COMMAND,
        model=model,
        gpus=gpus,
        user_text=user_text,
        status=JobStatus.queued,
    )

    return RedirectResponse("/", status_code=303)


# =============================================================================
# API submit endpoints
# =============================================================================

@app.post("/api/jobs/query-llm")
def submit_query_llm_job_api(
    model: str = Form(...),
    gpus: int = Form(1),
    user_text: str = Form("hello"),
    x_broker_token: Optional[str] = Header(default=None),
):
    verify_broker_token(x_broker_token)

    validate_query_llm_args(
        model=model,
        gpus=gpus,
        user_text=user_text,
    )

    job_id = str(uuid.uuid4())

    job = Job(
        id=job_id,
        command=QUERY_LLM_COMMAND,
        model=model,
        gpus=gpus,
        user_text=user_text,
        status=JobStatus.queued,
    )

    jobs[job_id] = job
    return job


# =============================================================================
# Worker polling and result posting
# =============================================================================

@app.get("/api/next-job")
def get_next_job(x_broker_token: Optional[str] = Header(default=None)):
    verify_broker_token(x_broker_token)

    for job in jobs.values():
        if job.status == JobStatus.queued:
            job.status = JobStatus.running

            return {
                "id": job.id,
                "command": job.command,
                "model": job.model,
                "gpus": job.gpus,
                "user_text": job.user_text,
            }

    return {"id": None}


@app.post("/api/jobs/{job_id}/result")
def post_result(
    job_id: str,
    result: str = Form(...),
    success: bool = Form(...),
    x_broker_token: Optional[str] = Header(default=None),
):
    verify_broker_token(x_broker_token)

    if job_id not in jobs:
        raise HTTPException(status_code=404, detail="Job not found")

    job = jobs[job_id]
    job.result = result
    job.status = JobStatus.done if success else JobStatus.failed

    return job


@app.get("/api/jobs")
def list_jobs(x_broker_token: Optional[str] = Header(default=None)):
    verify_broker_token(x_broker_token)
    return {"jobs": list(jobs.values())}


@app.get("/api/jobs/{job_id}")
def get_job(
    job_id: str,
    x_broker_token: Optional[str] = Header(default=None),
):
    verify_broker_token(x_broker_token)

    if job_id not in jobs:
        raise HTTPException(status_code=404, detail="Job not found")

    return jobs[job_id]


@app.post("/api/clear")
def clear_jobs(x_broker_token: Optional[str] = Header(default=None)):
    verify_broker_token(x_broker_token)

    jobs.clear()

    return {
        "status": "cleared",
        "jobs_count": len(jobs),
    }