llama-ui-termux 0.4.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Llama-UI contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: llama-ui-termux
3
+ Version: 0.4.3
4
+ Summary: A Rich terminal interface for llama.cpp
5
+ Author: Llama-UI contributors
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Environment :: Console
9
+ Classifier: Operating System :: Android
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: rich>=13.7.0
16
+ Dynamic: license-file
17
+
18
+ # Llama-UI 0.4.0
19
+
20
+ A Python package providing a Rich-powered terminal frontend for `llama.cpp`, designed with Termux on Android in mind.
21
+
22
+ ## Install in Termux
23
+
24
+ First make sure Python and pip are available:
25
+
26
+ ```bash
27
+ pkg install python
28
+ ```
29
+
30
+ Extract this project ZIP, enter the extracted `Llama-UI-Python` directory, then install it:
31
+
32
+ ```bash
33
+ python -m pip install .
34
+ ```
35
+
36
+ Run the application:
37
+
38
+ ```bash
39
+ llama-ui
40
+ ```
41
+
42
+ You can also launch it as a Python module:
43
+
44
+ ```bash
45
+ python -m llama_ui
46
+ ```
47
+
48
+ No Bash launcher or shell installer is included. The `llama-ui` command is created by Python packaging.
49
+
50
+ ## Requirements
51
+
52
+ - Python 3.9 or newer
53
+ - `rich` (installed automatically by pip from `pyproject.toml`)
54
+ - A working `llama.cpp` build that provides `llama-server`
55
+
56
+ Llama-UI does not include or compile llama.cpp itself.
57
+
58
+ ## First launch
59
+
60
+ The setup wizard asks which llama.cpp build you use:
61
+
62
+ 1. **Termux repository package** — uses `llama-server` from your `PATH`.
63
+ 2. **Compiled from source** — asks for the directory containing `llama-server` and the directories containing its shared libraries.
64
+
65
+ It then asks for your GGUF model folder and startup flags. After selecting a model, you can set its system prompt and generation parameters. Both are saved separately for each GGUF model and loaded automatically when you switch models; models without custom values use the defaults.
66
+
67
+ ## Features
68
+
69
+ - Rich menus, tables, panels and Markdown rendering.
70
+ - Import/copy a local `.gguf` file.
71
+ - Download a public Hugging Face GGUF using its repository ID and exact filename.
72
+ - Configure llama-server startup flags, per-model system prompts, and per-model generation parameters (temperature, top_p, top_k and repeat_penalty).
73
+ - Chat commands:
74
+ - `/edit` — edit the last user message and submit it again.
75
+ - `/regen` — regenerate the answer to the last user message.
76
+ - `/new` — start a fresh conversation.
77
+ - `/save` — save the current conversation.
78
+ - `/exit` — return to the main menu.
79
+ - Ctrl+C interrupts a response while it is streaming.
80
+ - History: view, load and delete saved conversations.
81
+ - System prompt: view, edit and delete the selected model’s prompt.
82
+ - Server controls: start, stop and inspect logs.
83
+
84
+ ## Startup flags
85
+
86
+ Enter `llama-server` flags only, for example:
87
+
88
+ ```text
89
+ -c 4096 -t 4 -ngl 0
90
+ ```
91
+
92
+ Llama-UI adds the selected model (`-m`), host and port itself. Do not include those options in the flags field.
93
+
94
+ ## Source build library paths
95
+
96
+ For source builds, enter the directory containing the `llama-server` binary and the directories containing its shared libraries. The app sets `LD_LIBRARY_PATH` for the server process. Exact paths vary by build configuration.
97
+
98
+ ## Configuration files
99
+
100
+ - Configuration, per-model generation parameters, and per-model system prompts: `~/.config/llama-ui/config.json`
101
+ - Chat history: `~/.config/llama-ui/chats/`
102
+ - Server log: `~/.config/llama-ui/server.log`
103
+ - Default model folder: `~/models`
104
+
105
+ ## Important notes
106
+
107
+ - Check GGUF file size before downloading; models may be several GB and use substantial mobile data.
108
+ - Public Hugging Face files are supported; private/gated repositories are not.
109
+ - Generation speed is approximate words/second, not tokenizer-accurate tokens/second.
110
+ - GPU offload depends on your particular llama.cpp build and Android device.
111
+ - The app starts/stops servers it launches itself. It does not automatically stop a server that was already running.
112
+ - This is a local source install (`pip install .`), not yet a published package on PyPI. Publishing to PyPI would require a package account and release process.
@@ -0,0 +1,95 @@
1
+ # Llama-UI 0.4.0
2
+
3
+ A Python package providing a Rich-powered terminal frontend for `llama.cpp`, designed with Termux on Android in mind.
4
+
5
+ ## Install in Termux
6
+
7
+ First make sure Python and pip are available:
8
+
9
+ ```bash
10
+ pkg install python
11
+ ```
12
+
13
+ Extract this project ZIP, enter the extracted `Llama-UI-Python` directory, then install it:
14
+
15
+ ```bash
16
+ python -m pip install .
17
+ ```
18
+
19
+ Run the application:
20
+
21
+ ```bash
22
+ llama-ui
23
+ ```
24
+
25
+ You can also launch it as a Python module:
26
+
27
+ ```bash
28
+ python -m llama_ui
29
+ ```
30
+
31
+ No Bash launcher or shell installer is included. The `llama-ui` command is created by Python packaging.
32
+
33
+ ## Requirements
34
+
35
+ - Python 3.9 or newer
36
+ - `rich` (installed automatically by pip from `pyproject.toml`)
37
+ - A working `llama.cpp` build that provides `llama-server`
38
+
39
+ Llama-UI does not include or compile llama.cpp itself.
40
+
41
+ ## First launch
42
+
43
+ The setup wizard asks which llama.cpp build you use:
44
+
45
+ 1. **Termux repository package** — uses `llama-server` from your `PATH`.
46
+ 2. **Compiled from source** — asks for the directory containing `llama-server` and the directories containing its shared libraries.
47
+
48
+ It then asks for your GGUF model folder and startup flags. After selecting a model, you can set its system prompt and generation parameters. Both are saved separately for each GGUF model and loaded automatically when you switch models; models without custom values use the defaults.
49
+
50
+ ## Features
51
+
52
+ - Rich menus, tables, panels and Markdown rendering.
53
+ - Import/copy a local `.gguf` file.
54
+ - Download a public Hugging Face GGUF using its repository ID and exact filename.
55
+ - Configure llama-server startup flags, per-model system prompts, and per-model generation parameters (temperature, top_p, top_k and repeat_penalty).
56
+ - Chat commands:
57
+ - `/edit` — edit the last user message and submit it again.
58
+ - `/regen` — regenerate the answer to the last user message.
59
+ - `/new` — start a fresh conversation.
60
+ - `/save` — save the current conversation.
61
+ - `/exit` — return to the main menu.
62
+ - Ctrl+C interrupts a response while it is streaming.
63
+ - History: view, load and delete saved conversations.
64
+ - System prompt: view, edit and delete the selected model’s prompt.
65
+ - Server controls: start, stop and inspect logs.
66
+
67
+ ## Startup flags
68
+
69
+ Enter `llama-server` flags only, for example:
70
+
71
+ ```text
72
+ -c 4096 -t 4 -ngl 0
73
+ ```
74
+
75
+ Llama-UI adds the selected model (`-m`), host and port itself. Do not include those options in the flags field.
76
+
77
+ ## Source build library paths
78
+
79
+ For source builds, enter the directory containing the `llama-server` binary and the directories containing its shared libraries. The app sets `LD_LIBRARY_PATH` for the server process. Exact paths vary by build configuration.
80
+
81
+ ## Configuration files
82
+
83
+ - Configuration, per-model generation parameters, and per-model system prompts: `~/.config/llama-ui/config.json`
84
+ - Chat history: `~/.config/llama-ui/chats/`
85
+ - Server log: `~/.config/llama-ui/server.log`
86
+ - Default model folder: `~/models`
87
+
88
+ ## Important notes
89
+
90
+ - Check GGUF file size before downloading; models may be several GB and use substantial mobile data.
91
+ - Public Hugging Face files are supported; private/gated repositories are not.
92
+ - Generation speed is approximate words/second, not tokenizer-accurate tokens/second.
93
+ - GPU offload depends on your particular llama.cpp build and Android device.
94
+ - The app starts/stops servers it launches itself. It does not automatically stop a server that was already running.
95
+ - This is a local source install (`pip install .`), not yet a published package on PyPI. Publishing to PyPI would require a package account and release process.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "llama-ui-termux"
7
+ version = "0.4.3"
8
+ description = "A Rich terminal interface for llama.cpp"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "Llama-UI contributors" }]
13
+ dependencies = [
14
+ "rich>=13.7.0"
15
+ ]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Environment :: Console",
19
+ "Operating System :: Android",
20
+ "Operating System :: POSIX :: Linux",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ ]
23
+
24
+ [project.scripts]
25
+ llama-ui = "llama_ui.cli:run"
26
+
27
+ [tool.setuptools]
28
+ package-dir = {"" = "src"}
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ __version__ = "0.4.3"
2
+ __app_name__ = "Llama-UI"
@@ -0,0 +1,4 @@
1
+ from .app import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,909 @@
1
+ #!/usr/bin/env python3
2
+ """Llama-UI 0.3 — Rich terminal interface for llama.cpp."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shlex
8
+ import shutil
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ import urllib.error
14
+ import urllib.parse
15
+ import urllib.request
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+
19
+ try:
20
+ from rich.console import Console
21
+ from rich.panel import Panel
22
+ from rich.markdown import Markdown
23
+ from rich.prompt import Prompt, Confirm
24
+ from rich.table import Table
25
+ from rich.text import Text
26
+ from rich import box
27
+ except ImportError:
28
+ print("Missing dependency: rich\nInstall it with: python -m pip install rich")
29
+ raise SystemExit(1)
30
+
31
+ APP = "Llama-UI"
32
+ VERSION = "0.4.3"
33
+ console = Console()
34
+ CFG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "llama-ui"
35
+ CFG_FILE = CFG_DIR / "config.json"
36
+ CHATS_DIR = CFG_DIR / "chats"
37
+ LOG_FILE = CFG_DIR / "server.log"
38
+
39
+ DEFAULTS = {
40
+ "setup_complete": False,
41
+ "install_type": "termux-package",
42
+ "server_binary": "llama-server",
43
+ "binary_dir": "",
44
+ "library_dirs": [],
45
+ "model_dir": str(Path.home() / "models"),
46
+ "model": "",
47
+ "startup_flags": "-c 4096 -t 4 -ngl 0",
48
+ "host": "127.0.0.1",
49
+ "port": 8080,
50
+ "temperature": 0.7,
51
+ "top_p": 0.9,
52
+ "top_k": 40,
53
+ "repeat_penalty": 1.1,
54
+ "timeout": 900,
55
+ "system_prompt": "",
56
+ }
57
+ cfg: dict = {}
58
+ server_proc: subprocess.Popen | None = None
59
+ chat: list[dict[str, str]] = []
60
+ chat_title = "New chat"
61
+
62
+
63
+ def load_config() -> None:
64
+ global cfg
65
+ CFG_DIR.mkdir(parents=True, exist_ok=True)
66
+ cfg = DEFAULTS.copy()
67
+ try:
68
+ saved = json.loads(CFG_FILE.read_text(encoding="utf-8"))
69
+ if isinstance(saved, dict):
70
+ cfg.update(saved)
71
+ except (OSError, ValueError):
72
+ pass
73
+
74
+ # Migrate old global generation parameters to the currently selected
75
+ # model. Other models start with DEFAULTS and can be configured separately.
76
+ model_settings = cfg.get("model_settings")
77
+ if not isinstance(model_settings, dict):
78
+ model_settings = {}
79
+ cfg["model_settings"] = model_settings
80
+ selected = model_settings_key()
81
+ if selected and selected not in model_settings:
82
+ legacy_keys = ("temperature", "top_p", "top_k", "repeat_penalty")
83
+ model_settings[selected] = {
84
+ key: cfg.get(key, DEFAULTS[key]) for key in legacy_keys
85
+ }
86
+ save_config()
87
+
88
+ # A legacy global system prompt belongs only to the model selected during
89
+ # migration. If no model is selected yet, migrate it lazily on first use.
90
+ migrate_legacy_system_prompt()
91
+
92
+ Path(cfg["model_dir"]).expanduser().mkdir(parents=True, exist_ok=True)
93
+
94
+
95
+ def save_config() -> None:
96
+ CFG_DIR.mkdir(parents=True, exist_ok=True)
97
+ temp = CFG_FILE.with_suffix(".tmp")
98
+ temp.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8")
99
+ temp.replace(CFG_FILE)
100
+
101
+
102
+ def pause(message: str = "Press Enter to continue") -> None:
103
+ Prompt.ask(f"[dim]{message}[/dim]", default="")
104
+
105
+
106
+ def heading(subtitle: str = "") -> None:
107
+ console.clear()
108
+ console.print(Panel.fit(
109
+ f"[bold bright_cyan]L L A M A - U I[/bold bright_cyan] [dim]v{VERSION}[/dim]"
110
+ + (f"\n[dim]{subtitle}[/dim]" if subtitle else ""),
111
+ border_style="bright_cyan",
112
+ ))
113
+
114
+
115
+ def menu(title: str, choices: list[str]) -> str:
116
+ table = Table(box=box.SIMPLE, show_header=False, pad_edge=False)
117
+ table.add_column("Key", style="bold cyan", width=5)
118
+ table.add_column("Action")
119
+ for i, choice in enumerate(choices, 1):
120
+ table.add_row(str(i), choice)
121
+ console.print(Panel(table, title=title, border_style="cyan"))
122
+ valid = [str(i) for i in range(1, len(choices) + 1)]
123
+ return Prompt.ask("Choose", choices=valid)
124
+
125
+
126
+ def find_source_binary(directory: Path) -> Path | None:
127
+ candidates = [
128
+ directory / "llama-server",
129
+ directory / "build" / "bin" / "llama-server",
130
+ directory / "bin" / "llama-server",
131
+ ]
132
+ for candidate in candidates:
133
+ if candidate.is_file():
134
+ return candidate.resolve()
135
+ return None
136
+
137
+
138
+ def setup_wizard(force: bool = False) -> None:
139
+ if cfg.get("setup_complete") and not force:
140
+ return
141
+ heading("First-run setup")
142
+ console.print("Let's connect Llama-UI to your existing [bold]llama.cpp[/bold] build.")
143
+ console.print("This does not compile or install llama.cpp for you.\n")
144
+ kind = menu("Which llama.cpp build do you use?", [
145
+ "Pre-compiled package from the Termux repository",
146
+ "Compiled from source",
147
+ ])
148
+ if kind == "1":
149
+ cfg["install_type"] = "termux-package"
150
+ cfg["server_binary"] = Prompt.ask(
151
+ "Server command", default="llama-server"
152
+ ).strip() or "llama-server"
153
+ cfg["binary_dir"] = ""
154
+ cfg["library_dirs"] = []
155
+ console.print("[green]Using the command from your Termux PATH.[/green]")
156
+ else:
157
+ cfg["install_type"] = "source"
158
+ default_dir = str(Path.home() / "llama.cpp" / "build" / "bin")
159
+ binary_dir = Prompt.ask(
160
+ "Directory containing the compiled llama-server binary",
161
+ default=default_dir,
162
+ ).strip()
163
+ binary_dir = str(Path(binary_dir).expanduser())
164
+ cfg["binary_dir"] = binary_dir
165
+ found = find_source_binary(Path(binary_dir).expanduser())
166
+ if found:
167
+ cfg["server_binary"] = str(found)
168
+ console.print(f"[green]Found:[/green] {found}")
169
+ else:
170
+ candidate = Path(binary_dir).expanduser()
171
+ if candidate.name == "llama-server":
172
+ cfg["server_binary"] = str(candidate)
173
+ else:
174
+ cfg["server_binary"] = str(candidate / "llama-server")
175
+ console.print("[yellow]Could not verify the binary yet; saved the expected path.[/yellow]")
176
+ libs = Prompt.ask(
177
+ "Library directories (comma-separated; include build/bin, build/src or ggml paths as needed)",
178
+ default=binary_dir,
179
+ )
180
+ cfg["library_dirs"] = [
181
+ str(Path(item.strip()).expanduser())
182
+ for item in libs.split(",") if item.strip()
183
+ ]
184
+
185
+ cfg["model_dir"] = str(Path(Prompt.ask(
186
+ "Folder for GGUF models", default=cfg["model_dir"]
187
+ )).expanduser())
188
+ Path(cfg["model_dir"]).mkdir(parents=True, exist_ok=True)
189
+
190
+ console.print("\n[bold]Startup flags[/bold]")
191
+ console.print("Enter llama-server flags only. Llama-UI adds the model, host and port.")
192
+ cfg["startup_flags"] = Prompt.ask(
193
+ "Flags", default=str(cfg.get("startup_flags", DEFAULTS["startup_flags"]))
194
+ )
195
+ console.print("\n[bold]System prompt[/bold]")
196
+ current_prompt = get_system_prompt()
197
+ if selected_model():
198
+ if Confirm.ask("Set a system prompt for the selected model now?", default=bool(current_prompt)):
199
+ save_system_prompt(Prompt.ask("System prompt", default=current_prompt))
200
+ else:
201
+ save_system_prompt("")
202
+ else:
203
+ console.print("[dim]Select a GGUF model first to configure its system prompt. You can do this later in Settings.[/dim]")
204
+
205
+ cfg["setup_complete"] = True
206
+ save_config()
207
+ console.print("\n[green]Setup saved.[/green] These settings load automatically next time.")
208
+ pause()
209
+
210
+
211
+ def model_files() -> list[Path]:
212
+ folder = Path(cfg["model_dir"]).expanduser()
213
+ folder.mkdir(parents=True, exist_ok=True)
214
+ return sorted(folder.glob("*.gguf"), key=lambda p: p.name.lower())
215
+
216
+
217
+ def selected_model() -> Path | None:
218
+ raw = str(cfg.get("model", "")).strip()
219
+ if not raw:
220
+ return None
221
+ path = Path(raw).expanduser()
222
+ if path.is_file() and path.suffix.lower() == ".gguf":
223
+ return path
224
+ path = Path(cfg["model_dir"]).expanduser() / raw
225
+ return path if path.is_file() else None
226
+
227
+
228
+ def model_settings_key() -> str | None:
229
+ """Return a stable key for the selected model's saved settings."""
230
+ model = selected_model()
231
+ if model is None:
232
+ return None
233
+ try:
234
+ return str(model.resolve())
235
+ except OSError:
236
+ return str(model.expanduser())
237
+
238
+
239
+ def migrate_legacy_system_prompt() -> None:
240
+ legacy = str(cfg.get("system_prompt", "")).strip()
241
+ key = model_settings_key()
242
+ if not legacy or not key:
243
+ return
244
+ prompts = cfg.get("model_system_prompts")
245
+ if not isinstance(prompts, dict):
246
+ prompts = {}
247
+ cfg["model_system_prompts"] = prompts
248
+ if key not in prompts:
249
+ prompts[key] = legacy
250
+ cfg["system_prompt"] = ""
251
+ save_config()
252
+
253
+
254
+ def get_system_prompt() -> str:
255
+ migrate_legacy_system_prompt()
256
+ key = model_settings_key()
257
+ prompts = cfg.get("model_system_prompts", {})
258
+ if not key or not isinstance(prompts, dict):
259
+ return ""
260
+ return str(prompts.get(key, ""))
261
+
262
+
263
+ def save_system_prompt(value: str) -> None:
264
+ key = model_settings_key()
265
+ if key is None:
266
+ raise ValueError("Select a GGUF model before editing its system prompt.")
267
+ prompts = cfg.setdefault("model_system_prompts", {})
268
+ if not isinstance(prompts, dict):
269
+ prompts = {}
270
+ cfg["model_system_prompts"] = prompts
271
+ prompts[key] = value
272
+ save_config()
273
+
274
+
275
+ def generation_settings() -> dict[str, float | int]:
276
+ """Get generation parameters for the selected model."""
277
+ key = model_settings_key()
278
+ saved = cfg.get("model_settings", {})
279
+ per_model = saved.get(key, {}) if key and isinstance(saved, dict) else {}
280
+ if not isinstance(per_model, dict):
281
+ per_model = {}
282
+ return {
283
+ name: per_model.get(name, DEFAULTS[name])
284
+ for name in ("temperature", "top_p", "top_k", "repeat_penalty")
285
+ }
286
+
287
+
288
+ def save_generation_settings(values: dict) -> None:
289
+ """Save generation parameters against the selected model only."""
290
+ key = model_settings_key()
291
+ if key is None:
292
+ raise ValueError("Select a GGUF model before editing generation parameters.")
293
+ all_settings = cfg.setdefault("model_settings", {})
294
+ if not isinstance(all_settings, dict):
295
+ all_settings = {}
296
+ cfg["model_settings"] = all_settings
297
+ current = generation_settings()
298
+ current.update(values)
299
+ all_settings[key] = current
300
+ save_config()
301
+
302
+
303
+ def server_environment() -> dict[str, str]:
304
+ env = os.environ.copy()
305
+ if cfg.get("install_type") == "source":
306
+ dirs = [str(Path(p).expanduser()) for p in cfg.get("library_dirs", [])]
307
+ existing = [p for p in dirs if Path(p).is_dir()]
308
+ old = env.get("LD_LIBRARY_PATH", "")
309
+ env["LD_LIBRARY_PATH"] = os.pathsep.join(existing + ([old] if old else []))
310
+ return env
311
+
312
+
313
+ def binary_path() -> str:
314
+ return str(cfg.get("server_binary") or "llama-server")
315
+
316
+
317
+ def endpoint(path: str) -> str:
318
+ return f"http://{cfg['host']}:{int(cfg['port'])}{path}"
319
+
320
+
321
+ def server_online() -> bool:
322
+ try:
323
+ req = urllib.request.Request(endpoint("/health"))
324
+ with urllib.request.urlopen(req, timeout=1.5) as response:
325
+ return response.status < 500
326
+ except Exception:
327
+ return False
328
+
329
+
330
+ def start_server() -> str:
331
+ global server_proc
332
+ if server_online():
333
+ return "A server is already responding at the configured address."
334
+ model = selected_model()
335
+ if not model:
336
+ return "Select or import a GGUF model first."
337
+ binary = binary_path()
338
+ if cfg.get("install_type") == "termux-package" and shutil.which(binary) is None:
339
+ return f"Cannot find '{binary}' on PATH. Check your llama.cpp package installation."
340
+ if cfg.get("install_type") == "source" and not Path(binary).is_file():
341
+ return f"Server binary not found: {binary}"
342
+ try:
343
+ flags = shlex.split(str(cfg.get("startup_flags", "")))
344
+ cmd = [binary, *flags, "-m", str(model), "--host", str(cfg["host"]),
345
+ "--port", str(int(cfg["port"]))]
346
+ CFG_DIR.mkdir(parents=True, exist_ok=True)
347
+ with LOG_FILE.open("ab") as log:
348
+ server_proc = subprocess.Popen(
349
+ cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
350
+ env=server_environment(), start_new_session=True,
351
+ )
352
+ time.sleep(1.0)
353
+ if server_proc.poll() is not None:
354
+ code = server_proc.returncode
355
+ server_proc = None
356
+ return f"llama-server exited with code {code}. Check {LOG_FILE}"
357
+ return f"Started llama-server (PID {server_proc.pid})."
358
+ except (OSError, ValueError) as exc:
359
+ return f"Could not start server: {exc}"
360
+
361
+
362
+ def stop_server() -> str:
363
+ global server_proc
364
+ if not server_proc or server_proc.poll() is not None:
365
+ server_proc = None
366
+ return "No server started by this Llama-UI session."
367
+ try:
368
+ os.killpg(server_proc.pid, signal.SIGTERM)
369
+ server_proc.wait(timeout=6)
370
+ server_proc = None
371
+ return "Server stopped."
372
+ except subprocess.TimeoutExpired:
373
+ os.killpg(server_proc.pid, signal.SIGKILL)
374
+ server_proc = None
375
+ return "Server force-stopped."
376
+ except OSError as exc:
377
+ return f"Could not stop server: {exc}"
378
+
379
+
380
+ def stream_completion(history: list[dict], on_chunk) -> None:
381
+ params = generation_settings()
382
+ body = {
383
+ "model": "local-model",
384
+ "messages": history,
385
+ "stream": True,
386
+ "temperature": float(params["temperature"]),
387
+ "top_p": float(params["top_p"]),
388
+ "top_k": int(params["top_k"]),
389
+ "repeat_penalty": float(params["repeat_penalty"]),
390
+ }
391
+ req = urllib.request.Request(
392
+ endpoint("/v1/chat/completions"),
393
+ data=json.dumps(body).encode("utf-8"),
394
+ headers={"Content-Type": "application/json"},
395
+ method="POST",
396
+ )
397
+ with urllib.request.urlopen(req, timeout=int(cfg["timeout"])) as response:
398
+ for raw in response:
399
+ line = raw.decode("utf-8", "replace").strip()
400
+ if not line.startswith("data:"):
401
+ continue
402
+ data = line[5:].strip()
403
+ if data == "[DONE]":
404
+ break
405
+ try:
406
+ obj = json.loads(data)
407
+ chunk = obj["choices"][0].get("delta", {}).get("content", "")
408
+ if chunk:
409
+ on_chunk(chunk)
410
+ except (ValueError, KeyError, IndexError, TypeError):
411
+ continue
412
+
413
+
414
+ def render_markdown(content: str) -> None:
415
+ try:
416
+ console.print(Markdown(content or "*(empty response)*"))
417
+ except Exception:
418
+ console.print(content)
419
+
420
+
421
+ def save_chat() -> Path:
422
+ CHATS_DIR.mkdir(parents=True, exist_ok=True)
423
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
424
+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in chat_title)[:48]
425
+ path = CHATS_DIR / f"{stamp}-{safe or 'chat'}.json"
426
+ path.write_text(json.dumps({
427
+ "title": chat_title, "messages": chat,
428
+ "saved_at": datetime.now().isoformat(timespec="seconds"),
429
+ }, indent=2, ensure_ascii=False), encoding="utf-8")
430
+ return path
431
+
432
+
433
+ def load_chat(path: Path) -> None:
434
+ global chat, chat_title
435
+ data = json.loads(path.read_text(encoding="utf-8"))
436
+ loaded = data.get("messages", [])
437
+ if not isinstance(loaded, list):
438
+ raise ValueError("Invalid chat format")
439
+ chat = [
440
+ {"role": str(m["role"]), "content": str(m["content"])}
441
+ for m in loaded
442
+ if isinstance(m, dict) and m.get("role") in ("user", "assistant")
443
+ and "content" in m
444
+ ]
445
+ chat_title = str(data.get("title") or path.stem)
446
+
447
+
448
+ def download_hf(repo: str, filename: str) -> str:
449
+ repo = repo.strip().strip("/")
450
+ filename = filename.strip().lstrip("/")
451
+ if not repo or "/" not in repo or not filename or ".." in Path(filename).parts:
452
+ return "Enter a repository as owner/name and an exact file path."
453
+ name = Path(filename).name
454
+ dest = Path(cfg["model_dir"]).expanduser() / name
455
+ if dest.exists():
456
+ return f"Already exists: {dest}"
457
+ url = (
458
+ "https://huggingface.co/" + urllib.parse.quote(repo, safe="/")
459
+ + "/resolve/main/" + urllib.parse.quote(filename, safe="/") + "?download=true"
460
+ )
461
+ temp = dest.with_suffix(dest.suffix + ".part")
462
+ try:
463
+ request = urllib.request.Request(url, headers={"User-Agent": "Llama-UI/0.3"})
464
+ with urllib.request.urlopen(request, timeout=90) as response, temp.open("wb") as out:
465
+ total = int(response.headers.get("Content-Length", "0") or 0)
466
+ done = 0
467
+ while True:
468
+ chunk = response.read(1024 * 1024)
469
+ if not chunk:
470
+ break
471
+ out.write(chunk)
472
+ done += len(chunk)
473
+ if total:
474
+ console.print(
475
+ f"\rDownloaded {done / 1024**3:.2f} / {total / 1024**3:.2f} GB",
476
+ end="",
477
+ )
478
+ temp.replace(dest)
479
+ console.print()
480
+ return f"Downloaded {dest.name} ({done / 1024**3:.2f} GB)."
481
+ except Exception as exc:
482
+ try:
483
+ temp.unlink(missing_ok=True)
484
+ except OSError:
485
+ pass
486
+ console.print()
487
+ return f"Download failed: {exc}"
488
+
489
+
490
+ def choose_model() -> None:
491
+ files = model_files()
492
+ if not files:
493
+ console.print("[yellow]No GGUF files found in the model folder.[/yellow]")
494
+ return
495
+ table = Table(title="Available GGUF models")
496
+ table.add_column("#", style="cyan", justify="right")
497
+ table.add_column("Model")
498
+ table.add_column("Size", justify="right")
499
+ for i, path in enumerate(files, 1):
500
+ mark = " [green]✓[/green]" if selected_model() == path else ""
501
+ table.add_row(str(i), path.name + mark, f"{path.stat().st_size / 1024**3:.2f} GB")
502
+ console.print(table)
503
+ choice = Prompt.ask("Model number", default="1")
504
+ try:
505
+ cfg["model"] = str(files[int(choice) - 1])
506
+ save_config()
507
+ console.print(f"[green]Selected {files[int(choice)-1].name}[/green]")
508
+ except (ValueError, IndexError):
509
+ console.print("[red]Invalid model number.[/red]")
510
+
511
+
512
+ def models_menu() -> None:
513
+ while True:
514
+ heading("Models")
515
+ console.print(f"Model folder: [cyan]{cfg['model_dir']}[/cyan]")
516
+ current = selected_model()
517
+ console.print(f"Selected: [bold]{current.name if current else 'None'}[/bold]\n")
518
+ choice = menu("Model manager", [
519
+ "Choose a local GGUF model",
520
+ "Import/copy a GGUF file from another folder",
521
+ "Download a public Hugging Face GGUF",
522
+ "Change model folder",
523
+ "Back",
524
+ ])
525
+ if choice == "1":
526
+ choose_model()
527
+ pause()
528
+ elif choice == "2":
529
+ source = Path(Prompt.ask("Full path to the .gguf file").strip()).expanduser()
530
+ if not source.is_file() or source.suffix.lower() != ".gguf":
531
+ console.print("[red]That is not an existing .gguf file.[/red]")
532
+ else:
533
+ dest = Path(cfg["model_dir"]).expanduser() / source.name
534
+ if dest.exists() and not Confirm.ask("File exists. Replace it?", default=False):
535
+ console.print("Import cancelled.")
536
+ else:
537
+ try:
538
+ shutil.copy2(source, dest)
539
+ cfg["model"] = str(dest)
540
+ save_config()
541
+ console.print(f"[green]Imported and selected {dest.name}[/green]")
542
+ except OSError as exc:
543
+ console.print(f"[red]Import failed: {exc}[/red]")
544
+ pause()
545
+ elif choice == "3":
546
+ console.print("[yellow]Check the model's file size before downloading; GGUF files can be several GB.[/yellow]")
547
+ repo = Prompt.ask("Hugging Face repository (owner/name)")
548
+ filename = Prompt.ask("Exact GGUF filename/path in that repository")
549
+ if Confirm.ask("Start download?", default=False):
550
+ console.print(download_hf(repo, filename))
551
+ else:
552
+ console.print("Download cancelled.")
553
+ pause()
554
+ elif choice == "4":
555
+ folder = Path(Prompt.ask("Model folder", default=cfg["model_dir"])).expanduser()
556
+ folder.mkdir(parents=True, exist_ok=True)
557
+ cfg["model_dir"] = str(folder)
558
+ save_config()
559
+ else:
560
+ return
561
+
562
+
563
+ def chat_menu() -> None:
564
+ global chat, chat_title
565
+ while True:
566
+ heading("Chat")
567
+ model = selected_model()
568
+ status = "[green]ONLINE[/green]" if server_online() else "[red]OFFLINE[/red]"
569
+ console.print(f"Model: [bold]{model.name if model else 'not selected'}[/bold] · Server: {status}\n")
570
+ if chat:
571
+ for item in chat:
572
+ if item["role"] == "user":
573
+ console.print(Panel(item["content"], title="You", border_style="cyan"))
574
+ else:
575
+ console.print(Panel(Markdown(item["content"] or "*(generating)*"),
576
+ title="Llama", border_style="green"))
577
+ else:
578
+ console.print(Panel("Start by typing a message below.\n\n"
579
+ "Commands: /edit, /regen, /new, /save, /exit",
580
+ title="Conversation", border_style="dim"))
581
+
582
+ prompt = Prompt.ask("\n[bold cyan]You[/bold cyan] (or /command)")
583
+ command = prompt.strip().lower()
584
+ if command in ("/exit", "/quit", "/q"):
585
+ return
586
+ if command in ("/new", "/clear"):
587
+ if chat and Confirm.ask("Save this conversation first?", default=True):
588
+ console.print(f"Saved: {save_chat()}")
589
+ chat = []
590
+ chat_title = Prompt.ask("New chat title", default="New chat")
591
+ continue
592
+ if command == "/save":
593
+ try:
594
+ console.print(f"[green]Saved:[/green] {save_chat()}")
595
+ except OSError as exc:
596
+ console.print(f"[red]Save failed: {exc}[/red]")
597
+ pause()
598
+ continue
599
+ if command == "/edit":
600
+ index = next((i for i in range(len(chat)-1, -1, -1)
601
+ if chat[i]["role"] == "user"), None)
602
+ if index is None:
603
+ console.print("[yellow]There is no user message to edit.[/yellow]")
604
+ pause()
605
+ continue
606
+ old = chat[index]["content"]
607
+ edited = Prompt.ask("Edit your last message", default=old)
608
+ if not edited.strip():
609
+ continue
610
+ del chat[index:]
611
+ prompt = edited
612
+ elif command == "/regen":
613
+ while chat and chat[-1]["role"] == "assistant":
614
+ chat.pop()
615
+ if not chat or chat[-1]["role"] != "user":
616
+ console.print("[yellow]No previous prompt to regenerate.[/yellow]")
617
+ pause()
618
+ continue
619
+ prompt = ""
620
+ elif prompt.startswith("/"):
621
+ console.print("[yellow]Unknown command. Use /edit /regen /new /save /exit[/yellow]")
622
+ pause()
623
+ continue
624
+
625
+ if prompt.strip():
626
+ chat.append({"role": "user", "content": prompt})
627
+ if not chat or chat[-1]["role"] != "user":
628
+ continue
629
+ if not server_online():
630
+ console.print("[red]Server is offline. Start it from the Server menu.[/red]")
631
+ pause()
632
+ continue
633
+ # Some llama.cpp chat templates only accept alternating user/assistant
634
+ # roles and reject a separate "system" message. Fold the saved system
635
+ # prompt into the first user message to preserve that role sequence.
636
+ history = [
637
+ {"role": item["role"], "content": item["content"]}
638
+ for item in chat
639
+ ]
640
+ system_prompt = get_system_prompt().strip()
641
+ if system_prompt:
642
+ first_user = next(
643
+ (item for item in history if item["role"] == "user"), None
644
+ )
645
+ if first_user is not None:
646
+ first_user["content"] = (
647
+ "System instructions (follow these throughout the conversation):\n"
648
+ + system_prompt
649
+ + "\n\nUser message:\n"
650
+ + first_user["content"]
651
+ )
652
+ answer = ""
653
+ started = time.perf_counter()
654
+ console.print("\n[bold green]Llama[/bold green]")
655
+ try:
656
+ def receive(piece: str) -> None:
657
+ nonlocal answer
658
+ answer += piece
659
+ console.print(piece, end="", markup=False, highlight=False)
660
+ stream_completion(history, receive)
661
+ elapsed = max(0.001, time.perf_counter() - started)
662
+ chat.append({"role": "assistant", "content": answer})
663
+ console.print(f"\n[dim]Completed in {elapsed:.1f}s · approximate {len(answer.split())/elapsed:.1f} words/sec[/dim]")
664
+ except urllib.error.HTTPError as exc:
665
+ detail = exc.read(1000).decode("utf-8", "replace")
666
+ chat.append({"role": "assistant", "content": f"HTTP {exc.code}: {detail}"})
667
+ console.print(f"\n[red]HTTP {exc.code}: {detail}[/red]")
668
+ except KeyboardInterrupt:
669
+ chat.append({"role": "assistant", "content": answer})
670
+ console.print("\n[yellow]Generation interrupted by Ctrl+C.[/yellow]")
671
+ except Exception as exc:
672
+ chat.append({"role": "assistant", "content": f"Request error: {exc}"})
673
+ console.print(f"\n[red]Request error: {exc}[/red]")
674
+ pause()
675
+
676
+
677
+ def history_menu() -> None:
678
+ CHATS_DIR.mkdir(parents=True, exist_ok=True)
679
+ while True:
680
+ heading("History")
681
+ files = sorted(CHATS_DIR.glob("*.json"), reverse=True)
682
+ if not files:
683
+ console.print("[dim]No saved chats yet.[/dim]")
684
+ pause()
685
+ return
686
+ table = Table(box=box.SIMPLE)
687
+ table.add_column("#", style="cyan")
688
+ table.add_column("Saved chat")
689
+ for i, path in enumerate(files, 1):
690
+ table.add_row(str(i), path.name)
691
+ console.print(table)
692
+ choice = menu("History", ["View a chat", "Load a chat into Chat", "Delete a chat", "Back"])
693
+ if choice == "4":
694
+ return
695
+ number = Prompt.ask("Chat number")
696
+ try:
697
+ path = files[int(number) - 1]
698
+ data = json.loads(path.read_text(encoding="utf-8"))
699
+ if choice == "1":
700
+ heading(path.name)
701
+ for item in data.get("messages", []):
702
+ console.print(Panel(
703
+ Markdown(str(item.get("content", ""))) if item.get("role") == "assistant"
704
+ else str(item.get("content", "")),
705
+ title=str(item.get("role", "message")).title(),
706
+ ))
707
+ pause()
708
+ elif choice == "2":
709
+ load_chat(path)
710
+ console.print("[green]Chat loaded. Open Chat to continue.[/green]")
711
+ pause()
712
+ elif choice == "3":
713
+ if Confirm.ask(f"Delete {path.name}?", default=False):
714
+ path.unlink()
715
+ console.print("[green]Deleted.[/green]")
716
+ except (ValueError, IndexError, OSError, json.JSONDecodeError, TypeError) as exc:
717
+ console.print(f"[red]Could not process that chat: {exc}[/red]")
718
+ pause()
719
+
720
+
721
+ def system_prompt_menu() -> None:
722
+ while True:
723
+ heading("System prompt")
724
+ model = selected_model()
725
+ if model is None:
726
+ console.print("[yellow]Select a GGUF model first. System prompts are saved separately for each model.[/yellow]")
727
+ pause()
728
+ return
729
+ current = get_system_prompt()
730
+ console.print(f"[dim]Model: {model.name}[/dim]")
731
+ if current:
732
+ console.print(Panel(current, title="Current system prompt", border_style="cyan"))
733
+ else:
734
+ console.print("[dim]No system prompt is set for this model. The model will use its own default behavior.[/dim]")
735
+ choice = menu("System prompt", ["Edit / set", "Delete", "Back"])
736
+ if choice == "1":
737
+ save_system_prompt(Prompt.ask("System prompt", default=current))
738
+ console.print(f"[green]System prompt saved for {model.name}.[/green]")
739
+ pause()
740
+ elif choice == "2":
741
+ if current and Confirm.ask("Delete this model's saved system prompt?", default=False):
742
+ save_system_prompt("")
743
+ console.print(f"[green]System prompt deleted for {model.name}.[/green]")
744
+ pause()
745
+ else:
746
+ return
747
+
748
+
749
+ def settings_menu() -> None:
750
+ while True:
751
+ heading("Settings")
752
+ params = generation_settings()
753
+ model = selected_model()
754
+ table = Table(box=box.SIMPLE)
755
+ table.add_column("Setting", style="cyan")
756
+ table.add_column("Value")
757
+ for key in ("install_type", "server_binary", "binary_dir", "library_dirs",
758
+ "startup_flags", "model_dir", "host", "port"):
759
+ table.add_row(key, str(cfg.get(key)))
760
+ console.print(table)
761
+ if model:
762
+ console.print(f"System prompt: {'[green]set[/green]' if get_system_prompt() else '[dim]not set[/dim]'} for {model.name}")
763
+ gen_table = Table(title=f"Generation parameters — {model.name}", box=box.SIMPLE)
764
+ gen_table.add_column("Parameter", style="cyan")
765
+ gen_table.add_column("Value")
766
+ for key, value in params.items():
767
+ gen_table.add_row(key, str(value))
768
+ console.print(gen_table)
769
+ else:
770
+ console.print("[yellow]Select a GGUF model to view or edit its generation parameters.[/yellow]")
771
+ choice = menu("Settings", [
772
+ "Run installation setup again",
773
+ "Edit startup flags",
774
+ "Edit server address (host / port)",
775
+ "Edit generation parameters for selected model",
776
+ "System prompt for selected model",
777
+ "Back",
778
+ ])
779
+ if choice == "1":
780
+ setup_wizard(force=True)
781
+ elif choice == "2":
782
+ console.print("Enter llama-server flags only; model, host and port are added separately.")
783
+ cfg["startup_flags"] = Prompt.ask("Startup flags", default=str(cfg["startup_flags"]))
784
+ save_config()
785
+ elif choice == "3":
786
+ cfg["host"] = Prompt.ask("Host", default=str(cfg["host"]))
787
+ try:
788
+ cfg["port"] = int(Prompt.ask("Port", default=str(cfg["port"])))
789
+ if not 1 <= cfg["port"] <= 65535:
790
+ raise ValueError("Port must be 1–65535")
791
+ save_config()
792
+ except ValueError as exc:
793
+ console.print(f"[red]Invalid port: {exc}[/red]")
794
+ pause()
795
+ elif choice == "4":
796
+ if not model:
797
+ console.print("[yellow]Choose a model first in Models.[/yellow]")
798
+ pause()
799
+ continue
800
+ updated = {}
801
+ for key, typ in (("temperature", float), ("top_p", float),
802
+ ("top_k", int), ("repeat_penalty", float)):
803
+ raw = Prompt.ask(key, default=str(params[key]))
804
+ try:
805
+ updated[key] = typ(raw)
806
+ except ValueError:
807
+ console.print(f"[yellow]Kept previous {key} value.[/yellow]")
808
+ save_generation_settings(updated)
809
+ console.print(f"[green]Generation parameters saved for {model.name}.[/green]")
810
+ pause()
811
+ elif choice == "5":
812
+ system_prompt_menu()
813
+ else:
814
+ return
815
+
816
+
817
+ def server_menu() -> None:
818
+ while True:
819
+ heading("Server")
820
+ console.print(f"Binary: [cyan]{binary_path()}[/cyan]")
821
+ console.print(f"Endpoint: {endpoint('/v1/chat/completions')}")
822
+ console.print(f"Status: {'[green]ONLINE[/green]' if server_online() else '[red]OFFLINE[/red]'}")
823
+ choice = menu("Server controls", ["Start", "Stop", "Show recent log", "Back"])
824
+ if choice == "1":
825
+ console.print(start_server())
826
+ pause()
827
+ elif choice == "2":
828
+ console.print(stop_server())
829
+ pause()
830
+ elif choice == "3":
831
+ heading("Server log")
832
+ try:
833
+ lines = LOG_FILE.read_text(errors="replace").splitlines()[-35:]
834
+ console.print("\n".join(lines) if lines else "[dim]Log is empty.[/dim]")
835
+ except OSError:
836
+ console.print("[dim]No log file yet.[/dim]")
837
+ pause()
838
+ else:
839
+ return
840
+
841
+
842
+ def help_screen() -> None:
843
+ heading("Help")
844
+ console.print(Panel(
845
+ "[bold]First launch[/bold]\n"
846
+ "The setup wizard asks whether you use the Termux package or a source build. "
847
+ "For source builds, provide the binary directory and library directories.\n\n"
848
+ "[bold]Chat commands[/bold]\n"
849
+ "/edit Edit the last user message and send it again\n"
850
+ "/regen Generate a new answer for the last prompt\n"
851
+ "/new Start a fresh conversation\n"
852
+ "/save Save the current conversation\n"
853
+ "/exit Leave Chat\n"
854
+ "Ctrl+C interrupts a running generation.\n\n"
855
+ "[bold]Model manager[/bold]\n"
856
+ "Choose a local GGUF, import/copy one, or download a public Hugging Face file.\n\n"
857
+ "[bold]Configuration[/bold]\n"
858
+ f"{CFG_FILE}\n"
859
+ f"Chat history: {CHATS_DIR}\n"
860
+ f"Server log: {LOG_FILE}\n\n"
861
+ "[yellow]Note:[/yellow] GGUF downloads can be several GB. Check storage and mobile data first.",
862
+ title="Quick reference",
863
+ ))
864
+ pause()
865
+
866
+
867
+ def main() -> None:
868
+ load_config()
869
+ setup_wizard()
870
+ while True:
871
+ heading("Terminal workspace for llama.cpp")
872
+ model = selected_model()
873
+ console.print(f"Model: [bold]{model.name if model else 'not selected'}[/bold]")
874
+ console.print(f"Server: {'[green]ONLINE[/green]' if server_online() else '[red]OFFLINE[/red]'}")
875
+ choice = menu("Main menu", [
876
+ "Chat",
877
+ "Models — choose, import or download GGUF",
878
+ "Server — start, stop and logs",
879
+ "History — view, load or delete chats",
880
+ "Settings",
881
+ "System prompt — view, edit or delete",
882
+ "Help",
883
+ "Exit",
884
+ ])
885
+ if choice == "1":
886
+ chat_menu()
887
+ elif choice == "2":
888
+ models_menu()
889
+ elif choice == "3":
890
+ server_menu()
891
+ elif choice == "4":
892
+ history_menu()
893
+ elif choice == "5":
894
+ settings_menu()
895
+ elif choice == "6":
896
+ system_prompt_menu()
897
+ elif choice == "7":
898
+ help_screen()
899
+ else:
900
+ if server_proc and server_proc.poll() is None:
901
+ console.print(f"[yellow]Server remains running (PID {server_proc.pid}).[/yellow]")
902
+ break
903
+
904
+
905
+ if __name__ == "__main__":
906
+ try:
907
+ main()
908
+ except KeyboardInterrupt:
909
+ console.print("\n[yellow]Exiting Llama-UI.[/yellow]")
@@ -0,0 +1,4 @@
1
+ from .app import main
2
+
3
+ def run() -> None:
4
+ main()
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: llama-ui-termux
3
+ Version: 0.4.3
4
+ Summary: A Rich terminal interface for llama.cpp
5
+ Author: Llama-UI contributors
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Environment :: Console
9
+ Classifier: Operating System :: Android
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: rich>=13.7.0
16
+ Dynamic: license-file
17
+
18
+ # Llama-UI 0.4.0
19
+
20
+ A Python package providing a Rich-powered terminal frontend for `llama.cpp`, designed with Termux on Android in mind.
21
+
22
+ ## Install in Termux
23
+
24
+ First make sure Python and pip are available:
25
+
26
+ ```bash
27
+ pkg install python
28
+ ```
29
+
30
+ Extract this project ZIP, enter the extracted `Llama-UI-Python` directory, then install it:
31
+
32
+ ```bash
33
+ python -m pip install .
34
+ ```
35
+
36
+ Run the application:
37
+
38
+ ```bash
39
+ llama-ui
40
+ ```
41
+
42
+ You can also launch it as a Python module:
43
+
44
+ ```bash
45
+ python -m llama_ui
46
+ ```
47
+
48
+ No Bash launcher or shell installer is included. The `llama-ui` command is created by Python packaging.
49
+
50
+ ## Requirements
51
+
52
+ - Python 3.9 or newer
53
+ - `rich` (installed automatically by pip from `pyproject.toml`)
54
+ - A working `llama.cpp` build that provides `llama-server`
55
+
56
+ Llama-UI does not include or compile llama.cpp itself.
57
+
58
+ ## First launch
59
+
60
+ The setup wizard asks which llama.cpp build you use:
61
+
62
+ 1. **Termux repository package** — uses `llama-server` from your `PATH`.
63
+ 2. **Compiled from source** — asks for the directory containing `llama-server` and the directories containing its shared libraries.
64
+
65
+ It then asks for your GGUF model folder and startup flags. After selecting a model, you can set its system prompt and generation parameters. Both are saved separately for each GGUF model and loaded automatically when you switch models; models without custom values use the defaults.
66
+
67
+ ## Features
68
+
69
+ - Rich menus, tables, panels and Markdown rendering.
70
+ - Import/copy a local `.gguf` file.
71
+ - Download a public Hugging Face GGUF using its repository ID and exact filename.
72
+ - Configure llama-server startup flags, per-model system prompts, and per-model generation parameters (temperature, top_p, top_k and repeat_penalty).
73
+ - Chat commands:
74
+ - `/edit` — edit the last user message and submit it again.
75
+ - `/regen` — regenerate the answer to the last user message.
76
+ - `/new` — start a fresh conversation.
77
+ - `/save` — save the current conversation.
78
+ - `/exit` — return to the main menu.
79
+ - Ctrl+C interrupts a response while it is streaming.
80
+ - History: view, load and delete saved conversations.
81
+ - System prompt: view, edit and delete the selected model’s prompt.
82
+ - Server controls: start, stop and inspect logs.
83
+
84
+ ## Startup flags
85
+
86
+ Enter `llama-server` flags only, for example:
87
+
88
+ ```text
89
+ -c 4096 -t 4 -ngl 0
90
+ ```
91
+
92
+ Llama-UI adds the selected model (`-m`), host and port itself. Do not include those options in the flags field.
93
+
94
+ ## Source build library paths
95
+
96
+ For source builds, enter the directory containing the `llama-server` binary and the directories containing its shared libraries. The app sets `LD_LIBRARY_PATH` for the server process. Exact paths vary by build configuration.
97
+
98
+ ## Configuration files
99
+
100
+ - Configuration, per-model generation parameters, and per-model system prompts: `~/.config/llama-ui/config.json`
101
+ - Chat history: `~/.config/llama-ui/chats/`
102
+ - Server log: `~/.config/llama-ui/server.log`
103
+ - Default model folder: `~/models`
104
+
105
+ ## Important notes
106
+
107
+ - Check GGUF file size before downloading; models may be several GB and use substantial mobile data.
108
+ - Public Hugging Face files are supported; private/gated repositories are not.
109
+ - Generation speed is approximate words/second, not tokenizer-accurate tokens/second.
110
+ - GPU offload depends on your particular llama.cpp build and Android device.
111
+ - The app starts/stops servers it launches itself. It does not automatically stop a server that was already running.
112
+ - This is a local source install (`pip install .`), not yet a published package on PyPI. Publishing to PyPI would require a package account and release process.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/llama_ui/__init__.py
5
+ src/llama_ui/__main__.py
6
+ src/llama_ui/app.py
7
+ src/llama_ui/cli.py
8
+ src/llama_ui_termux.egg-info/PKG-INFO
9
+ src/llama_ui_termux.egg-info/SOURCES.txt
10
+ src/llama_ui_termux.egg-info/dependency_links.txt
11
+ src/llama_ui_termux.egg-info/entry_points.txt
12
+ src/llama_ui_termux.egg-info/requires.txt
13
+ src/llama_ui_termux.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ llama-ui = llama_ui.cli:run