owenisas commited on
Commit
ae6d0c6
·
verified ·
1 Parent(s): d7f66ae

Add First-Principle AI Gradio app

Browse files
Files changed (3) hide show
  1. README.md +57 -8
  2. app.py +500 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,14 +1,63 @@
1
  ---
2
- title: First Principle AI
3
- emoji: 👀
4
  colorFrom: gray
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 6.16.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
11
- license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: "First-Principle AI"
3
+ emoji: "⚙️"
4
  colorFrom: gray
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: "6.14.0"
8
+ python_version: "3.12"
9
  app_file: app.py
10
+ fullWidth: true
11
+ header: mini
12
+ short_description: "Dense Gradio lab console for probing a Phase-3 Q8 GGUF."
13
+ suggested_hardware: zero-a10g
14
+ models:
15
+ - owenisas/phase-3-gguf
16
+ tags:
17
+ - gradio
18
+ - zerogpu
19
+ - llama-cpp
20
+ - gguf
21
+ - chatbot
22
+ - model-lab
23
+ - build-small-hackathon
24
+ license: mit
25
  ---
26
 
27
+ # First-Principle AI
28
+
29
+ First-Principle AI is a compact Gradio console for probing the
30
+ `owenisas/phase-3-gguf` Q8 GGUF model through
31
+ `llama-cpp-python`.
32
+
33
+ The UI is intentionally dense: chat, sampling controls, system prompt,
34
+ runtime state, model state, RAM check, and generation metrics are visible on
35
+ one screen.
36
+
37
+ ## Runtime Notes
38
+
39
+ - Model repo: `owenisas/phase-3-gguf`
40
+ - Model file: `model-Q8_0.gguf`
41
+ - Runtime: `llama-cpp-python`
42
+ - Hardware target: ZeroGPU
43
+ - Fallback behavior: visible runtime diagnostics instead of silent mock output
44
+ - Model loading: guarded runtime download/load, not build-time preload
45
+
46
+ ZeroGPU is a Gradio dynamic GPU runtime primarily documented around PyTorch
47
+ workloads. This app targets ZeroGPU as requested, but it also reports whether
48
+ the GGUF can actually load through llama.cpp on the current runtime. If the
49
+ runtime does not expose enough memory or a compatible llama.cpp backend, the
50
+ app returns a visible compatibility message.
51
+
52
+ The model is intentionally not preloaded during the Space build because the Q8
53
+ GGUF is 33.6 GB and can make build startup unreliable. The app resolves the Hub
54
+ file at runtime after checking memory and runtime compatibility. Hosted Spaces
55
+ also guard against remote-loading this file unless `PHASE3_FORCE_LOAD=1` is set,
56
+ so the default public demo stays responsive and transparent.
57
+
58
+ ## Local Smoke Test
59
+
60
+ ```bash
61
+ cd /Users/user/Documents/Automation-agents/hf-spaces/phase-3-gguf-lab
62
+ PHASE3_DISABLE_MODEL=1 python app.py
63
+ ```
app.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import re
6
+ import threading
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import gradio as gr
12
+ from huggingface_hub import HfApi, hf_hub_download
13
+
14
+ try:
15
+ import spaces
16
+ except Exception: # pragma: no cover - the package exists on HF ZeroGPU runtimes
17
+ spaces = None # type: ignore[assignment]
18
+
19
+ try:
20
+ from llama_cpp import Llama
21
+ except Exception as exc: # pragma: no cover - resolved in the Space runtime
22
+ Llama = None # type: ignore[assignment]
23
+ LLAMA_IMPORT_ERROR = exc
24
+ else:
25
+ LLAMA_IMPORT_ERROR = None
26
+
27
+
28
+ MODEL_REPO = os.getenv("PHASE3_MODEL_REPO", "owenisas/phase-3-gguf")
29
+ MODEL_FILE = os.getenv("PHASE3_MODEL_FILE", "model-Q8_0.gguf")
30
+ MODEL_LABEL = "First-Principle AI"
31
+ LOCAL_MODEL_PATH = Path("/Users/user/.lmstudio/models/owenisas/Phase-3-GGUF/model-Q8_0.gguf")
32
+ MAX_CONTEXT = int(os.getenv("PHASE3_MAX_CONTEXT", "4096"))
33
+ MIN_RAM_GB = float(os.getenv("PHASE3_MIN_RAM_GB", "38"))
34
+ FORCE_LOAD = os.getenv("PHASE3_FORCE_LOAD", "").lower() in {"1", "true", "yes"}
35
+ DISABLE_MODEL = os.getenv("PHASE3_DISABLE_MODEL", "").lower() in {"1", "true", "yes"}
36
+
37
+ MODEL_LOCK = threading.Lock()
38
+ MODEL: Any | None = None
39
+ MODEL_PATH: Path | None = None
40
+ MODEL_ERROR: str | None = None
41
+
42
+
43
+ def _gpu_decorator(fn):
44
+ if not FORCE_LOAD:
45
+ return fn
46
+ if spaces is None:
47
+ return fn
48
+ try:
49
+ return spaces.GPU(duration=120)(fn)
50
+ except Exception:
51
+ return fn
52
+
53
+
54
+ if spaces is not None:
55
+ try:
56
+ @spaces.GPU(duration=1)
57
+ def _zerogpu_startup_probe() -> str:
58
+ return "ZeroGPU configured"
59
+ except Exception:
60
+ def _zerogpu_startup_probe() -> str:
61
+ return "ZeroGPU helper importable"
62
+ else:
63
+ def _zerogpu_startup_probe() -> str:
64
+ return "ZeroGPU helper unavailable"
65
+
66
+
67
+ def _meminfo_gb() -> tuple[float | None, float | None]:
68
+ meminfo = Path("/proc/meminfo")
69
+ if not meminfo.exists():
70
+ return None, None
71
+ data: dict[str, int] = {}
72
+ for line in meminfo.read_text(encoding="utf-8", errors="ignore").splitlines():
73
+ match = re.match(r"^(\w+):\s+(\d+)\s+kB", line)
74
+ if match:
75
+ data[match.group(1)] = int(match.group(2))
76
+ total = data.get("MemTotal")
77
+ available = data.get("MemAvailable")
78
+ gb = 1024 * 1024
79
+ return (total / gb if total else None, available / gb if available else None)
80
+
81
+
82
+ def _safe_env_summary() -> dict[str, str]:
83
+ keys = [
84
+ "SPACE_ID",
85
+ "SPACE_HOST",
86
+ "SPACE_AUTHOR_NAME",
87
+ "SPACE_REPO_NAME",
88
+ "CUDA_VISIBLE_DEVICES",
89
+ "PHASE3_MODEL_REPO",
90
+ "PHASE3_MODEL_FILE",
91
+ "PHASE3_MAX_CONTEXT",
92
+ "PHASE3_FORCE_LOAD",
93
+ "PHASE3_DISABLE_MODEL",
94
+ ]
95
+ return {key: os.environ[key] for key in keys if key in os.environ}
96
+
97
+
98
+ def _repo_file_size() -> int | None:
99
+ try:
100
+ info = HfApi().model_info(MODEL_REPO, files_metadata=True)
101
+ except Exception:
102
+ return None
103
+ for sibling in info.siblings or []:
104
+ if sibling.rfilename == MODEL_FILE:
105
+ return getattr(sibling, "size", None)
106
+ return None
107
+
108
+
109
+ def _find_model_path() -> Path:
110
+ if DISABLE_MODEL:
111
+ raise RuntimeError("Model loading is disabled with PHASE3_DISABLE_MODEL=1.")
112
+
113
+ explicit = os.getenv("PHASE3_MODEL_PATH")
114
+ if explicit:
115
+ path = Path(explicit)
116
+ if path.exists():
117
+ return path
118
+ raise RuntimeError(f"PHASE3_MODEL_PATH does not exist: {explicit}")
119
+
120
+ if LOCAL_MODEL_PATH.exists():
121
+ return LOCAL_MODEL_PATH
122
+
123
+ downloaded = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
124
+ return Path(downloaded)
125
+
126
+
127
+ def _load_model() -> Any:
128
+ global MODEL, MODEL_PATH, MODEL_ERROR
129
+
130
+ if MODEL is not None:
131
+ return MODEL
132
+ if MODEL_ERROR is not None:
133
+ raise RuntimeError(MODEL_ERROR)
134
+ if Llama is None:
135
+ MODEL_ERROR = f"llama-cpp-python is not importable: {LLAMA_IMPORT_ERROR}"
136
+ raise RuntimeError(MODEL_ERROR)
137
+
138
+ with MODEL_LOCK:
139
+ if MODEL is not None:
140
+ return MODEL
141
+ if MODEL_ERROR is not None:
142
+ raise RuntimeError(MODEL_ERROR)
143
+
144
+ total_gb, available_gb = _meminfo_gb()
145
+ remote_size = _repo_file_size()
146
+ if (
147
+ not FORCE_LOAD
148
+ and os.getenv("SPACE_ID")
149
+ and remote_size is not None
150
+ and remote_size > 20 * 1024**3
151
+ ):
152
+ MODEL_ERROR = (
153
+ f"Hosted Space guard is active: {MODEL_FILE} is "
154
+ f"{remote_size / (1024 ** 3):.1f} GB. This avoids a slow "
155
+ "runtime download/load on ZeroGPU for a GGUF backend that may "
156
+ "not be CUDA-compatible. Set PHASE3_FORCE_LOAD=1 only after "
157
+ "confirming the hardware and llama.cpp backend can support it."
158
+ )
159
+ raise RuntimeError(MODEL_ERROR)
160
+ if not FORCE_LOAD and total_gb is not None and total_gb < MIN_RAM_GB:
161
+ MODEL_ERROR = (
162
+ f"Runtime has {total_gb:.1f} GB RAM, below the guarded load threshold "
163
+ f"of {MIN_RAM_GB:.1f} GB for the 31 GB Q8 GGUF. Set PHASE3_FORCE_LOAD=1 "
164
+ "only on hardware with enough memory."
165
+ )
166
+ raise RuntimeError(MODEL_ERROR)
167
+
168
+ path = _find_model_path()
169
+ MODEL_PATH = path
170
+ n_threads = int(os.getenv("PHASE3_THREADS", str(max(1, min(8, os.cpu_count() or 2)))))
171
+ if "PHASE3_N_GPU_LAYERS" in os.environ:
172
+ n_gpu_layers = int(os.environ["PHASE3_N_GPU_LAYERS"])
173
+ elif os.getenv("CUDA_VISIBLE_DEVICES"):
174
+ n_gpu_layers = -1
175
+ else:
176
+ n_gpu_layers = 0
177
+
178
+ try:
179
+ MODEL = Llama(
180
+ model_path=str(path),
181
+ n_ctx=MAX_CONTEXT,
182
+ n_threads=n_threads,
183
+ n_gpu_layers=n_gpu_layers,
184
+ verbose=False,
185
+ )
186
+ except Exception as exc:
187
+ MODEL_ERROR = f"Model load failed: {exc}"
188
+ raise RuntimeError(MODEL_ERROR) from exc
189
+
190
+ return MODEL
191
+
192
+
193
+ def _format_prompt(system_prompt: str, history: list[dict[str, str]], message: str) -> str:
194
+ system = system_prompt.strip() or "You are a precise, direct model in a technical lab console."
195
+ turns = [f"<|im_start|>system\n{system}<|im_end|>"]
196
+ for item in history[-10:]:
197
+ role = item.get("role", "user")
198
+ content = item.get("content", "")
199
+ if role in {"user", "assistant"} and content:
200
+ turns.append(f"<|im_start|>{role}\n{content}<|im_end|>")
201
+ turns.append(f"<|im_start|>user\n{message}<|im_end|>")
202
+ turns.append("<|im_start|>assistant\n")
203
+ return "\n".join(turns)
204
+
205
+
206
+ @_gpu_decorator
207
+ def _complete(
208
+ prompt: str,
209
+ max_tokens: int,
210
+ temperature: float,
211
+ top_p: float,
212
+ repeat_penalty: float,
213
+ ) -> tuple[str, dict[str, Any]]:
214
+ model = _load_model()
215
+ started = time.time()
216
+ output = model(
217
+ prompt,
218
+ max_tokens=int(max_tokens),
219
+ temperature=float(temperature),
220
+ top_p=float(top_p),
221
+ repeat_penalty=float(repeat_penalty),
222
+ stop=["<|im_end|>", "<|endoftext|>"],
223
+ echo=False,
224
+ )
225
+ elapsed = max(time.time() - started, 0.001)
226
+ text = output["choices"][0]["text"].strip()
227
+ usage = output.get("usage") or {}
228
+ completion_tokens = usage.get("completion_tokens") or max(1, len(text.split()))
229
+ return text, {
230
+ "elapsed": elapsed,
231
+ "completion_tokens": completion_tokens,
232
+ "tokens_per_second": completion_tokens / elapsed,
233
+ "usage": usage,
234
+ }
235
+
236
+
237
+ def _status_markdown() -> str:
238
+ total_gb, available_gb = _meminfo_gb()
239
+ size = _repo_file_size()
240
+ size_text = f"{size / (1024 ** 3):.1f} GB" if size else "unknown"
241
+ local_state = "present" if LOCAL_MODEL_PATH.exists() else "not present"
242
+ llama_state = "importable" if Llama is not None else f"missing ({LLAMA_IMPORT_ERROR})"
243
+ spaces_state = "importable" if spaces is not None else "not importable"
244
+ model_state = "loaded" if MODEL is not None else ("error" if MODEL_ERROR else "not loaded")
245
+ model_path = str(MODEL_PATH) if MODEL_PATH else "not resolved"
246
+ total_text = f"{total_gb:.1f} GB" if total_gb is not None else "unknown"
247
+ available_text = f"{available_gb:.1f} GB" if available_gb is not None else "unknown"
248
+ env = _safe_env_summary()
249
+ env_lines = "\n".join(f"- `{k}`: `{v}`" for k, v in env.items()) or "- No selected runtime env vars exposed."
250
+
251
+ return f"""### Runtime
252
+ - Model repo: `{MODEL_REPO}`
253
+ - Model file: `{MODEL_FILE}` ({size_text})
254
+ - Local development source: `{local_state}`
255
+ - Resolved model path: `{model_path}`
256
+ - llama.cpp runtime: `{llama_state}`
257
+ - ZeroGPU helper package: `{spaces_state}`
258
+ - Model state: `{model_state}`
259
+ - RAM: `{available_text}` available / `{total_text}` total
260
+ - Python: `{platform.python_version()}`
261
+
262
+ ### Selected Environment
263
+ {env_lines}
264
+ """
265
+
266
+
267
+ def _metrics_markdown(meta: dict[str, Any] | None = None) -> str:
268
+ if not meta:
269
+ return "Generation metrics will appear after a run."
270
+ return (
271
+ f"Elapsed: `{meta['elapsed']:.2f}s` \n"
272
+ f"Completion tokens: `{meta['completion_tokens']}` \n"
273
+ f"Approx tokens/sec: `{meta['tokens_per_second']:.2f}`"
274
+ )
275
+
276
+
277
+ def _clear() -> tuple[list[dict[str, str]], str, str, str]:
278
+ return [], "", _status_markdown(), _metrics_markdown()
279
+
280
+
281
+ def _chunk_text(text: str):
282
+ if not text:
283
+ yield ""
284
+ return
285
+ parts = re.split(r"(\s+)", text)
286
+ acc = ""
287
+ for part in parts:
288
+ acc += part
289
+ yield acc
290
+
291
+
292
+ def respond(
293
+ message: str,
294
+ history: list[dict[str, str]] | None,
295
+ system_prompt: str,
296
+ max_tokens: int,
297
+ temperature: float,
298
+ top_p: float,
299
+ repeat_penalty: float,
300
+ ) -> Any:
301
+ history = list(history or [])
302
+ message = (message or "").strip()
303
+ if not message:
304
+ yield history, "", _status_markdown(), _metrics_markdown()
305
+ return
306
+
307
+ prior = [item for item in history if item.get("role") in {"user", "assistant"}]
308
+ history.append({"role": "user", "content": message})
309
+ history.append({"role": "assistant", "content": "Loading runtime and preparing generation..."})
310
+ yield history, "", _status_markdown(), "Queued."
311
+
312
+ prompt = _format_prompt(system_prompt, prior, message)
313
+ try:
314
+ text, meta = _complete(prompt, max_tokens, temperature, top_p, repeat_penalty)
315
+ except Exception as exc:
316
+ text = (
317
+ "Runtime compatibility check failed.\n\n"
318
+ f"{exc}\n\n"
319
+ "This Space is configured for ZeroGPU, but the uploaded asset is a 31 GB Q8 GGUF. "
320
+ "ZeroGPU is primarily a Gradio/PyTorch dynamic GPU runtime, while this app uses "
321
+ "llama.cpp through llama-cpp-python. If the runtime cannot expose enough RAM or a "
322
+ "compatible llama.cpp CUDA backend, the model is intentionally not loaded instead "
323
+ "of crashing the Space."
324
+ )
325
+ meta = {"elapsed": 0.0, "completion_tokens": len(text.split()), "tokens_per_second": 0.0}
326
+
327
+ for partial in _chunk_text(text):
328
+ history[-1]["content"] = partial
329
+ yield history, "", _status_markdown(), _metrics_markdown(meta)
330
+
331
+
332
+ CSS = """
333
+ :root {
334
+ --phase-bg: #080b10;
335
+ --phase-panel: #111820;
336
+ --phase-panel-2: #0d131a;
337
+ --phase-border: #26323f;
338
+ --phase-text: #e8edf2;
339
+ --phase-muted: #9aa8b5;
340
+ --phase-accent: #4fb3ff;
341
+ --phase-good: #66d68a;
342
+ }
343
+ .gradio-container {
344
+ background: var(--phase-bg) !important;
345
+ color: var(--phase-text) !important;
346
+ max-width: none !important;
347
+ }
348
+ .phase-shell {
349
+ max-width: 1440px;
350
+ margin: 0 auto;
351
+ }
352
+ .phase-title {
353
+ border: 1px solid var(--phase-border);
354
+ background: linear-gradient(180deg, #121a23, #0b1118);
355
+ padding: 16px 18px;
356
+ border-radius: 8px;
357
+ margin-bottom: 12px;
358
+ }
359
+ .phase-title h1 {
360
+ font-size: 24px;
361
+ line-height: 1.15;
362
+ margin: 0 0 6px;
363
+ letter-spacing: 0;
364
+ }
365
+ .phase-title p {
366
+ color: var(--phase-muted);
367
+ margin: 0;
368
+ }
369
+ .phase-badge-row {
370
+ display: flex;
371
+ flex-wrap: wrap;
372
+ gap: 8px;
373
+ margin-top: 12px;
374
+ }
375
+ .phase-badge {
376
+ border: 1px solid var(--phase-border);
377
+ background: #0c131b;
378
+ color: var(--phase-muted);
379
+ border-radius: 999px;
380
+ padding: 5px 9px;
381
+ font-size: 12px;
382
+ }
383
+ .phase-badge strong {
384
+ color: var(--phase-text);
385
+ font-weight: 650;
386
+ }
387
+ .panel {
388
+ border-color: var(--phase-border) !important;
389
+ background: var(--phase-panel) !important;
390
+ border-radius: 8px !important;
391
+ }
392
+ label, .wrap, .prose, .markdown-body {
393
+ color: var(--phase-text) !important;
394
+ }
395
+ textarea, input {
396
+ background: #0b1118 !important;
397
+ color: var(--phase-text) !important;
398
+ border-color: var(--phase-border) !important;
399
+ }
400
+ button.primary {
401
+ background: var(--phase-accent) !important;
402
+ color: #06101a !important;
403
+ }
404
+ .message {
405
+ border-radius: 8px !important;
406
+ }
407
+ .chatbot {
408
+ background: var(--phase-panel-2) !important;
409
+ border: 1px solid var(--phase-border) !important;
410
+ }
411
+ @media (max-width: 900px) {
412
+ .phase-title h1 {
413
+ font-size: 20px;
414
+ }
415
+ }
416
+ """
417
+
418
+
419
+ with gr.Blocks(title="First-Principle AI", fill_width=True) as demo:
420
+ with gr.Column(elem_classes=["phase-shell"]):
421
+ gr.HTML(
422
+ """
423
+ <div class="phase-title">
424
+ <h1>First-Principle AI</h1>
425
+ <p>A dense Gradio console for probing the Phase-3 Q8 GGUF with visible runtime diagnostics.</p>
426
+ <div class="phase-badge-row">
427
+ <span class="phase-badge"><strong>Model</strong> owenisas/phase-3-gguf</span>
428
+ <span class="phase-badge"><strong>Runtime</strong> llama.cpp via llama-cpp-python</span>
429
+ <span class="phase-badge"><strong>Hardware target</strong> ZeroGPU with guarded fallback</span>
430
+ </div>
431
+ </div>
432
+ """
433
+ )
434
+
435
+ with gr.Row(equal_height=False):
436
+ with gr.Column(scale=7, min_width=420):
437
+ chatbot = gr.Chatbot(
438
+ label="Chat",
439
+ height=560,
440
+ buttons=["copy"],
441
+ elem_classes=["chatbot"],
442
+ )
443
+ prompt = gr.Textbox(
444
+ label="Prompt",
445
+ placeholder="Ask First-Principle AI for a concise systems analysis...",
446
+ lines=3,
447
+ max_lines=8,
448
+ autofocus=True,
449
+ )
450
+ with gr.Row():
451
+ send = gr.Button("Run", variant="primary")
452
+ stop = gr.Button("Stop", variant="stop")
453
+ clear = gr.Button("Clear")
454
+
455
+ gr.Examples(
456
+ examples=[
457
+ "Explain the difference between a good demo and a benchmark in five bullets.",
458
+ "Design a small-agent eval for a hackathon judging panel.",
459
+ "Summarize what runtime evidence matters before claiming a model is live.",
460
+ ],
461
+ inputs=prompt,
462
+ label="Example probes",
463
+ )
464
+
465
+ with gr.Column(scale=4, min_width=320):
466
+ system_prompt = gr.Textbox(
467
+ label="System prompt",
468
+ value="You are First-Principle AI in a model lab. Be direct, technical, and evidence-oriented.",
469
+ lines=4,
470
+ max_lines=8,
471
+ )
472
+ with gr.Row():
473
+ max_tokens = gr.Slider(64, 768, value=256, step=32, label="Max tokens")
474
+ temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.05, label="Temperature")
475
+ with gr.Row():
476
+ top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p")
477
+ repeat_penalty = gr.Slider(1.0, 1.4, value=1.08, step=0.01, label="Repeat penalty")
478
+
479
+ status = gr.Markdown(_status_markdown(), label="Runtime status")
480
+ metrics = gr.Markdown(_metrics_markdown(), label="Generation metrics")
481
+
482
+ run_event = send.click(
483
+ fn=respond,
484
+ inputs=[prompt, chatbot, system_prompt, max_tokens, temperature, top_p, repeat_penalty],
485
+ outputs=[chatbot, prompt, status, metrics],
486
+ show_progress="minimal",
487
+ )
488
+ submit_event = prompt.submit(
489
+ fn=respond,
490
+ inputs=[prompt, chatbot, system_prompt, max_tokens, temperature, top_p, repeat_penalty],
491
+ outputs=[chatbot, prompt, status, metrics],
492
+ show_progress="minimal",
493
+ )
494
+ stop.click(fn=None, inputs=None, outputs=None, cancels=[run_event, submit_event])
495
+ clear.click(fn=_clear, inputs=None, outputs=[chatbot, prompt, status, metrics])
496
+ demo.load(fn=lambda: (_status_markdown(), _metrics_markdown()), outputs=[status, metrics])
497
+
498
+
499
+ if __name__ == "__main__":
500
+ demo.queue(default_concurrency_limit=1).launch(css=CSS)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
2
+
3
+ gradio==6.14.0
4
+ huggingface-hub==1.17.0
5
+ spaces==0.50.2
6
+ llama-cpp-python==0.3.8