lemonpie-cli 0.2.0__py3-none-any.whl
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.
- lemonpie/__init__.py +0 -0
- lemonpie/_version.py +24 -0
- lemonpie/cli/__init__.py +0 -0
- lemonpie/cli/config_cmd.py +527 -0
- lemonpie/cli/parser.py +22 -0
- lemonpie/cli/ui.py +74 -0
- lemonpie/config.py +68 -0
- lemonpie/engine/__init__.py +0 -0
- lemonpie/engine/models.py +61 -0
- lemonpie/engine/ollama.py +49 -0
- lemonpie/main.py +180 -0
- lemonpie/paths.py +27 -0
- lemonpie/sessions/__init__.py +0 -0
- lemonpie/sessions/storage.py +179 -0
- lemonpie/time_utils.py +14 -0
- lemonpie_cli-0.2.0.dist-info/METADATA +154 -0
- lemonpie_cli-0.2.0.dist-info/RECORD +20 -0
- lemonpie_cli-0.2.0.dist-info/WHEEL +4 -0
- lemonpie_cli-0.2.0.dist-info/entry_points.txt +4 -0
- lemonpie_cli-0.2.0.dist-info/licenses/LICENSE +674 -0
lemonpie/__init__.py
ADDED
|
File without changes
|
lemonpie/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.2.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 2, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
lemonpie/cli/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
config_cmd.py (alias: lmConfig) — CLI for managing LemonPie configuration.
|
|
4
|
+
|
|
5
|
+
Usage examples:
|
|
6
|
+
lmConfig --init # Interactive setup wizard
|
|
7
|
+
lmConfig --host http://127.0.0.1:11434 # Set Ollama server URL
|
|
8
|
+
lmConfig --add-model qwen qwen2.5-coder:3b # Map an alias to a model
|
|
9
|
+
lmConfig --add-model qwen qwen2.5:1.5b --force # Reassign an existing alias
|
|
10
|
+
lmConfig --default-model qwen # Set default by alias or name
|
|
11
|
+
lmConfig --remove-model qwen # Clear alias or remove model
|
|
12
|
+
lmConfig --list-models # View configured models
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
from lemonpie.cli.ui import confirm
|
|
23
|
+
from lemonpie.config import (
|
|
24
|
+
config_file_path,
|
|
25
|
+
ensure_models_list,
|
|
26
|
+
is_valid_url,
|
|
27
|
+
load_config,
|
|
28
|
+
save_config,
|
|
29
|
+
)
|
|
30
|
+
from lemonpie.engine.models import (
|
|
31
|
+
find_by_alias,
|
|
32
|
+
find_by_name,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# lmConfig --init helpers
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def fetch_ollama_models(server):
|
|
41
|
+
"""GET /api/tags and return (list_of_name_strings, error_str_or_None).
|
|
42
|
+
|
|
43
|
+
Used by cmd_init to verify server reachability and discover installed
|
|
44
|
+
models in a single round-trip.
|
|
45
|
+
"""
|
|
46
|
+
try:
|
|
47
|
+
resp = httpx.get(f"{server.rstrip('/')}/api/tags", timeout=5.0)
|
|
48
|
+
resp.raise_for_status()
|
|
49
|
+
data = resp.json()
|
|
50
|
+
return [m["name"] for m in data.get("models", [])], None
|
|
51
|
+
except httpx.ConnectError:
|
|
52
|
+
return [], "Connection refused"
|
|
53
|
+
except httpx.TimeoutException:
|
|
54
|
+
return [], "Connection timed out"
|
|
55
|
+
except httpx.HTTPError as exc:
|
|
56
|
+
return [], f"HTTP error: {exc}"
|
|
57
|
+
except (json.JSONDecodeError, KeyError, TypeError) as exc:
|
|
58
|
+
return [], f"Invalid response format from server, {exc}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _prompt_model_selection(available_models):
|
|
62
|
+
"""Show a numbered list of server-installed models; return selected entries.
|
|
63
|
+
|
|
64
|
+
The user enters space-separated numbers (e.g. ``1 3``). For each chosen
|
|
65
|
+
model an optional alias is collected. Pressing Enter without typing
|
|
66
|
+
anything skips model registration entirely.
|
|
67
|
+
"""
|
|
68
|
+
print("\n Available models:")
|
|
69
|
+
for i, name in enumerate(available_models, 1):
|
|
70
|
+
print(f" {i}. {name}")
|
|
71
|
+
|
|
72
|
+
raw = input("\n Select models to add (e.g. 1 3), Enter to skip: ").strip()
|
|
73
|
+
if not raw:
|
|
74
|
+
return []
|
|
75
|
+
|
|
76
|
+
selected = []
|
|
77
|
+
seen: set[str] = set()
|
|
78
|
+
for token in raw.split():
|
|
79
|
+
try:
|
|
80
|
+
idx = int(token) - 1
|
|
81
|
+
except ValueError:
|
|
82
|
+
print(f" Skipping invalid token: {token!r}")
|
|
83
|
+
continue
|
|
84
|
+
if not (0 <= idx < len(available_models)):
|
|
85
|
+
print(f" Out of range, skipping: {token!r}")
|
|
86
|
+
continue
|
|
87
|
+
name = available_models[idx]
|
|
88
|
+
if name in seen:
|
|
89
|
+
continue
|
|
90
|
+
seen.add(name)
|
|
91
|
+
alias_raw = input(f" Alias for {name!r} (optional, Enter to skip): ").strip()
|
|
92
|
+
selected.append({"alias": alias_raw or None, "name": name})
|
|
93
|
+
|
|
94
|
+
return selected
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _prompt_model_manual():
|
|
98
|
+
"""Collect one or more model entries by hand (name + optional alias)."""
|
|
99
|
+
models = []
|
|
100
|
+
while True:
|
|
101
|
+
while True:
|
|
102
|
+
name = input(" Model name (e.g. qwen2.5-coder:3b): ").strip()
|
|
103
|
+
if name:
|
|
104
|
+
break
|
|
105
|
+
print(" Model name cannot be empty.")
|
|
106
|
+
alias_raw = input(" Alias (optional, Enter to skip): ").strip()
|
|
107
|
+
models.append({"alias": alias_raw or None, "name": name})
|
|
108
|
+
if not confirm(" Add another model?"):
|
|
109
|
+
break
|
|
110
|
+
return models
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _prompt_default(models):
|
|
114
|
+
"""Ask which of the configured models should be the default.
|
|
115
|
+
|
|
116
|
+
Returns the chosen model name, or None if the user declines / there are
|
|
117
|
+
no models to choose from.
|
|
118
|
+
"""
|
|
119
|
+
if not models:
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
if len(models) == 1:
|
|
123
|
+
if confirm(f' Set "{models[0]["name"]}" as the default model?'):
|
|
124
|
+
return models[0]["name"]
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
# Multiple models — let the user pick by number.
|
|
128
|
+
if not confirm(" Set a default model?"):
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
for i, m in enumerate(models, 1):
|
|
132
|
+
alias_disp = m.get("alias") or "<no alias>"
|
|
133
|
+
print(f" {i}. {alias_disp} -> {m['name']}")
|
|
134
|
+
|
|
135
|
+
while True:
|
|
136
|
+
raw = input(f" Enter number (1-{len(models)}): ").strip()
|
|
137
|
+
try:
|
|
138
|
+
idx = int(raw) - 1
|
|
139
|
+
if 0 <= idx < len(models):
|
|
140
|
+
return models[idx]["name"]
|
|
141
|
+
except ValueError:
|
|
142
|
+
pass
|
|
143
|
+
print(f" Invalid choice, enter 1-{len(models)}.")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------------------------------------------------------------------------
|
|
147
|
+
# lmConfig --init
|
|
148
|
+
# ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def cmd_init(force=False):
|
|
152
|
+
"""Interactive wizard: create or reset config.json from scratch.
|
|
153
|
+
|
|
154
|
+
Steps
|
|
155
|
+
-----
|
|
156
|
+
1. Warn if a config already exists; ask for confirmation to overwrite.
|
|
157
|
+
2. Prompt for the Ollama server URL (validated; loops on bad input).
|
|
158
|
+
3. Unless ``--force``, verify server reachability via ``GET /api/tags``.
|
|
159
|
+
- If reachable: present the installed-model list for selection.
|
|
160
|
+
- If unreachable: offer to continue without verification.
|
|
161
|
+
4. If no server models are available, offer manual model entry.
|
|
162
|
+
5. Optionally set a default model.
|
|
163
|
+
6. Save and print a summary.
|
|
164
|
+
|
|
165
|
+
``--force`` skips step 3 entirely (useful when the server is offline
|
|
166
|
+
during setup or to bypass alias-conflict checks on subsequent adds).
|
|
167
|
+
"""
|
|
168
|
+
path = config_file_path()
|
|
169
|
+
if os.path.exists(path):
|
|
170
|
+
print(f"Config already exists: {path}")
|
|
171
|
+
if not confirm("Reinitialize from scratch?"):
|
|
172
|
+
print("Aborted.")
|
|
173
|
+
return 1
|
|
174
|
+
|
|
175
|
+
print("\nLemonPie setup\n")
|
|
176
|
+
|
|
177
|
+
# ------------------------------------------------------------------
|
|
178
|
+
# Step 1: Server URL
|
|
179
|
+
# ------------------------------------------------------------------
|
|
180
|
+
default_server = "http://127.0.0.1:11434"
|
|
181
|
+
while True:
|
|
182
|
+
raw = input(f"Ollama server URL [{default_server}]: ").strip()
|
|
183
|
+
server = raw or default_server
|
|
184
|
+
if is_valid_url(server):
|
|
185
|
+
break
|
|
186
|
+
print(f" Invalid URL: {server!r}. Must start with http:// or https://.")
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------
|
|
189
|
+
# Step 2: Verify server & discover models
|
|
190
|
+
# ------------------------------------------------------------------
|
|
191
|
+
available_models: list[str] = []
|
|
192
|
+
server_ok = False
|
|
193
|
+
|
|
194
|
+
if force:
|
|
195
|
+
print(" Skipping server verification (--force).")
|
|
196
|
+
else:
|
|
197
|
+
print(f" Connecting to {server} ...", end="", flush=True)
|
|
198
|
+
available_models, err = fetch_ollama_models(server)
|
|
199
|
+
if err:
|
|
200
|
+
print(f" failed.\n {err}")
|
|
201
|
+
if not confirm(" Continue without verification?"):
|
|
202
|
+
print("Aborted.")
|
|
203
|
+
return 1
|
|
204
|
+
else:
|
|
205
|
+
server_ok = True
|
|
206
|
+
count = len(available_models)
|
|
207
|
+
label = f"{count} model(s) available" if count else "no models installed"
|
|
208
|
+
print(f" OK ({label})")
|
|
209
|
+
|
|
210
|
+
# ------------------------------------------------------------------
|
|
211
|
+
# Step 3: Select / add models
|
|
212
|
+
# ------------------------------------------------------------------
|
|
213
|
+
models: list[dict] = []
|
|
214
|
+
|
|
215
|
+
if available_models:
|
|
216
|
+
models = _prompt_model_selection(available_models)
|
|
217
|
+
else:
|
|
218
|
+
if server_ok:
|
|
219
|
+
# Reachable but empty — give actionable guidance.
|
|
220
|
+
print(" No models are installed on this server.")
|
|
221
|
+
print(" Run `ollama pull <model>` to install one, then")
|
|
222
|
+
print(" use `lmConfig --add-model <alias> <name>` to register it.")
|
|
223
|
+
|
|
224
|
+
if confirm(" Add a model manually?"):
|
|
225
|
+
models = _prompt_model_manual()
|
|
226
|
+
|
|
227
|
+
# ------------------------------------------------------------------
|
|
228
|
+
# Step 4: Default model
|
|
229
|
+
# ------------------------------------------------------------------
|
|
230
|
+
default = _prompt_default(models)
|
|
231
|
+
|
|
232
|
+
# ------------------------------------------------------------------
|
|
233
|
+
# Step 5: Save & summarise
|
|
234
|
+
# ------------------------------------------------------------------
|
|
235
|
+
cfg = {"server": server, "default": default, "models": models}
|
|
236
|
+
save_config(cfg)
|
|
237
|
+
|
|
238
|
+
print("\nConfig saved.")
|
|
239
|
+
print(f" Server : {server}")
|
|
240
|
+
print(f" Default: {default or '<none>'}")
|
|
241
|
+
if models:
|
|
242
|
+
for m in models:
|
|
243
|
+
mark = "*" if m.get("name") == default else " "
|
|
244
|
+
alias_disp = m.get("alias") or "<no alias>"
|
|
245
|
+
print(f" {mark} {alias_disp} -> {m['name']}")
|
|
246
|
+
else:
|
|
247
|
+
print(" No models configured yet.")
|
|
248
|
+
print(" Use `lmConfig --add-model <alias> <name>` to add models later.")
|
|
249
|
+
|
|
250
|
+
return 0
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ---------------------------------------------------------------------------
|
|
254
|
+
# Existing lmConfig sub-commands
|
|
255
|
+
# ---------------------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def cmd_set_host(cfg, host):
|
|
259
|
+
if not is_valid_url(host):
|
|
260
|
+
print(f"Invalid URL: {host}")
|
|
261
|
+
return 2
|
|
262
|
+
cfg["server"] = host
|
|
263
|
+
save_config(cfg)
|
|
264
|
+
print(f"Host set to {host}")
|
|
265
|
+
return 0
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def cmd_set_default(cfg, identifier):
|
|
269
|
+
"""
|
|
270
|
+
Set default by alias or full model name. Default stores the model 'name'.
|
|
271
|
+
"""
|
|
272
|
+
ensure_models_list(cfg)
|
|
273
|
+
|
|
274
|
+
# Try alias first
|
|
275
|
+
_, m = find_by_alias(cfg, identifier)
|
|
276
|
+
if m:
|
|
277
|
+
cfg["default"] = m["name"]
|
|
278
|
+
save_config(cfg)
|
|
279
|
+
print(f"Default model set to {m['name']} (alias: {identifier})")
|
|
280
|
+
return 0
|
|
281
|
+
|
|
282
|
+
# Try full model name
|
|
283
|
+
_, m = find_by_name(cfg, identifier)
|
|
284
|
+
if m:
|
|
285
|
+
cfg["default"] = m["name"]
|
|
286
|
+
save_config(cfg)
|
|
287
|
+
print(f"Default model set to {m['name']}")
|
|
288
|
+
return 0
|
|
289
|
+
|
|
290
|
+
print(
|
|
291
|
+
f'Model "{identifier}" not found.'
|
|
292
|
+
f" Use --list-models to see configured models."
|
|
293
|
+
f" Use --add-model to add a new model mapping."
|
|
294
|
+
)
|
|
295
|
+
return 2
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def cmd_add_model(cfg, alias, model_name, force=False):
|
|
299
|
+
"""
|
|
300
|
+
Add or update a model object: { "alias": <nullable>, "name": <model_name> }.
|
|
301
|
+
- Check model_name first, then alias.
|
|
302
|
+
- With --force: reassign alias to model_name and set previous alias to None.
|
|
303
|
+
- If models list is empty before adding, set the added model as the default.
|
|
304
|
+
"""
|
|
305
|
+
ensure_models_list(cfg)
|
|
306
|
+
models = cfg["models"]
|
|
307
|
+
|
|
308
|
+
# Remember whether models list was empty before changes (for default assignment)
|
|
309
|
+
was_empty = len(models) == 0
|
|
310
|
+
|
|
311
|
+
# Find existing entries
|
|
312
|
+
_idx_name, entry_by_name = find_by_name(cfg, model_name)
|
|
313
|
+
_idx_alias, entry_by_alias = find_by_alias(cfg, alias)
|
|
314
|
+
|
|
315
|
+
# Exact mapping exists -> no-op
|
|
316
|
+
if entry_by_alias and entry_by_name and entry_by_alias is entry_by_name:
|
|
317
|
+
print(f'Alias "{alias}" already maps to "{model_name}". No changes made.')
|
|
318
|
+
return 0
|
|
319
|
+
|
|
320
|
+
# If model_name exists under a different alias
|
|
321
|
+
if (
|
|
322
|
+
entry_by_name
|
|
323
|
+
and entry_by_name.get("alias")
|
|
324
|
+
and entry_by_name.get("alias") != alias
|
|
325
|
+
):
|
|
326
|
+
existing_alias = entry_by_name["alias"]
|
|
327
|
+
if not force:
|
|
328
|
+
print(
|
|
329
|
+
f'Model "{model_name}" is already mapped to alias "{existing_alias}". Use --force to reassign.'
|
|
330
|
+
)
|
|
331
|
+
return 2
|
|
332
|
+
# force: clear the old alias (set to None) but keep the model record
|
|
333
|
+
print(
|
|
334
|
+
f'Removing alias "{existing_alias}" from model "{model_name}". It will remain accessible by full name.'
|
|
335
|
+
)
|
|
336
|
+
entry_by_name["alias"] = None
|
|
337
|
+
|
|
338
|
+
# If alias exists and maps to a different model
|
|
339
|
+
if entry_by_alias and entry_by_alias.get("name") != model_name:
|
|
340
|
+
existing_model = entry_by_alias["name"]
|
|
341
|
+
if not force:
|
|
342
|
+
print(
|
|
343
|
+
f'Alias "{alias}" is already in use for model "{existing_model}". Please use a different alias or remove the existing mapping.'
|
|
344
|
+
)
|
|
345
|
+
return 2
|
|
346
|
+
# force: clear the alias on the existing model object (set to None),
|
|
347
|
+
# but keep the model object (do not delete it).
|
|
348
|
+
print(f'Clearing alias "{alias}" from model "{existing_model}" to reassign it.')
|
|
349
|
+
entry_by_alias["alias"] = None
|
|
350
|
+
|
|
351
|
+
# At this point:
|
|
352
|
+
# - if entry_by_name exists, it may have alias None (cleared above) or already equal to alias
|
|
353
|
+
# - if entry_by_alias existed and was for a different model, its alias is now None
|
|
354
|
+
# Assign alias to existing model object if present
|
|
355
|
+
if entry_by_name:
|
|
356
|
+
entry_by_name["alias"] = alias
|
|
357
|
+
save_config(cfg)
|
|
358
|
+
print(f'Assigned alias "{alias}" to existing model "{model_name}".')
|
|
359
|
+
# If models list was empty before, set default to this model name
|
|
360
|
+
if was_empty:
|
|
361
|
+
cfg["default"] = model_name
|
|
362
|
+
save_config(cfg)
|
|
363
|
+
print(f'Set default model to "{model_name}" (first configured model).')
|
|
364
|
+
return 0
|
|
365
|
+
|
|
366
|
+
# Otherwise, alias is free and model_name is new -> create new object
|
|
367
|
+
models.append({"alias": alias, "name": model_name})
|
|
368
|
+
save_config(cfg)
|
|
369
|
+
print(f"Added model mapping: {alias} -> {model_name}")
|
|
370
|
+
|
|
371
|
+
# If this was the first model added, make it the default
|
|
372
|
+
if was_empty:
|
|
373
|
+
cfg["default"] = model_name
|
|
374
|
+
save_config(cfg)
|
|
375
|
+
print(f'Set default model to "{model_name}" (first configured model).')
|
|
376
|
+
|
|
377
|
+
return 0
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def cmd_remove_model(cfg, identifier):
|
|
381
|
+
"""
|
|
382
|
+
Remove mapping by alias or by full model name.
|
|
383
|
+
- If identifier matches an alias: clear the alias (set to None).
|
|
384
|
+
- If identifier matches a model name: confirm and remove the model object entirely.
|
|
385
|
+
"""
|
|
386
|
+
ensure_models_list(cfg)
|
|
387
|
+
|
|
388
|
+
_idx_alias, entry_alias = find_by_alias(cfg, identifier)
|
|
389
|
+
if entry_alias:
|
|
390
|
+
# Clear alias only
|
|
391
|
+
if not confirm(
|
|
392
|
+
f'Clear alias "{identifier}" from model "{entry_alias["name"]}"? (model will remain accessible by full name)'
|
|
393
|
+
):
|
|
394
|
+
print("Aborted.")
|
|
395
|
+
return 1
|
|
396
|
+
entry_alias["alias"] = None
|
|
397
|
+
save_config(cfg)
|
|
398
|
+
print(f'Cleared alias "{identifier}" from model "{entry_alias["name"]}".')
|
|
399
|
+
return 0
|
|
400
|
+
|
|
401
|
+
idx_name, entry_name = find_by_name(cfg, identifier)
|
|
402
|
+
if entry_name:
|
|
403
|
+
# Remove entire model object
|
|
404
|
+
if not confirm(
|
|
405
|
+
f'Remove model "{identifier}" entirely from config? This will delete the record.'
|
|
406
|
+
):
|
|
407
|
+
print("Aborted.")
|
|
408
|
+
return 1
|
|
409
|
+
del cfg["models"][idx_name]
|
|
410
|
+
# If default pointed to this model name, clear it
|
|
411
|
+
if cfg.get("default") == identifier:
|
|
412
|
+
cfg["default"] = None
|
|
413
|
+
print("Removed default model because it referenced the deleted model.")
|
|
414
|
+
save_config(cfg)
|
|
415
|
+
print(f'Removed model "{identifier}".')
|
|
416
|
+
return 0
|
|
417
|
+
|
|
418
|
+
print(f'No model or alias matching "{identifier}" found.')
|
|
419
|
+
return 2
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def cmd_list_models(cfg):
|
|
423
|
+
ensure_models_list(cfg)
|
|
424
|
+
models = cfg.get("models", [])
|
|
425
|
+
if not models:
|
|
426
|
+
print("No models configured.")
|
|
427
|
+
return 0
|
|
428
|
+
default_name = cfg.get("default")
|
|
429
|
+
print("Configured models:")
|
|
430
|
+
for m in sorted(models, key=lambda x: (x.get("alias") or "", x.get("name"))):
|
|
431
|
+
alias = m.get("alias") if m.get("alias") is not None else "<none>"
|
|
432
|
+
mark = "*" if m.get("name") == default_name else " "
|
|
433
|
+
print(f"{mark} {alias} -> {m.get('name')}")
|
|
434
|
+
return 0
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def cmd_show(cfg):
|
|
438
|
+
print(json.dumps(cfg, indent=2, ensure_ascii=False))
|
|
439
|
+
return 0
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
# ---------------------------------------------------------------------------
|
|
443
|
+
# Parser & entry-point
|
|
444
|
+
# ---------------------------------------------------------------------------
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def build_parser():
|
|
448
|
+
parser = argparse.ArgumentParser(
|
|
449
|
+
prog="lmConfig",
|
|
450
|
+
description="Manage LemonPie configuration (config.json)",
|
|
451
|
+
)
|
|
452
|
+
parser.add_argument(
|
|
453
|
+
"--init",
|
|
454
|
+
action="store_true",
|
|
455
|
+
help="Interactive setup wizard: create or reinitialize config.json",
|
|
456
|
+
)
|
|
457
|
+
parser.add_argument("--host", help="Set Ollama host URL (http(s)://host:port)")
|
|
458
|
+
parser.add_argument(
|
|
459
|
+
"--default-model",
|
|
460
|
+
help="Set default model using alias or full name (must exist in models)",
|
|
461
|
+
)
|
|
462
|
+
parser.add_argument(
|
|
463
|
+
"--add-model",
|
|
464
|
+
nargs=2,
|
|
465
|
+
metavar=("ALIAS", "MODEL"),
|
|
466
|
+
help="Add model mapping: alias model_full_name",
|
|
467
|
+
)
|
|
468
|
+
parser.add_argument(
|
|
469
|
+
"--remove-model",
|
|
470
|
+
metavar="IDENTIFIER",
|
|
471
|
+
help="Remove a model mapping by alias or full name",
|
|
472
|
+
)
|
|
473
|
+
parser.add_argument(
|
|
474
|
+
"--list-models",
|
|
475
|
+
action="store_true",
|
|
476
|
+
help="List configured model aliases and names",
|
|
477
|
+
)
|
|
478
|
+
parser.add_argument("--show", action="store_true", help="Print full config.json")
|
|
479
|
+
parser.add_argument(
|
|
480
|
+
"--force",
|
|
481
|
+
action="store_true",
|
|
482
|
+
help="Force overwrite when adding a model; skip server verification with --init",
|
|
483
|
+
)
|
|
484
|
+
return parser
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def main():
|
|
488
|
+
parser = build_parser()
|
|
489
|
+
args = parser.parse_args()
|
|
490
|
+
|
|
491
|
+
# --init is handled before load_config() so it can decide for itself
|
|
492
|
+
# whether the file already exists without triggering auto-creation.
|
|
493
|
+
if args.init:
|
|
494
|
+
return cmd_init(force=args.force)
|
|
495
|
+
|
|
496
|
+
cfg = load_config()
|
|
497
|
+
|
|
498
|
+
# Dispatch
|
|
499
|
+
if args.host:
|
|
500
|
+
return cmd_set_host(cfg, args.host)
|
|
501
|
+
|
|
502
|
+
if args.default_model:
|
|
503
|
+
return cmd_set_default(cfg, args.default_model)
|
|
504
|
+
|
|
505
|
+
if args.add_model:
|
|
506
|
+
alias, model_name = args.add_model
|
|
507
|
+
return cmd_add_model(cfg, alias, model_name, force=args.force)
|
|
508
|
+
|
|
509
|
+
if args.remove_model:
|
|
510
|
+
return cmd_remove_model(cfg, args.remove_model)
|
|
511
|
+
|
|
512
|
+
if args.list_models:
|
|
513
|
+
return cmd_list_models(cfg)
|
|
514
|
+
|
|
515
|
+
if args.show:
|
|
516
|
+
return cmd_show(cfg)
|
|
517
|
+
|
|
518
|
+
parser.print_help()
|
|
519
|
+
return 0
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
if __name__ == "__main__":
|
|
523
|
+
try:
|
|
524
|
+
sys.exit(main() or 0)
|
|
525
|
+
except KeyboardInterrupt:
|
|
526
|
+
print("\nInterrupted.")
|
|
527
|
+
sys.exit(1)
|
lemonpie/cli/parser.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from lemonpie._version import __version__
|
|
5
|
+
except ImportError:
|
|
6
|
+
__version__ = "0.0.0.dev0"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_parser():
|
|
10
|
+
parser = argparse.ArgumentParser(prog="lm", description="Run LemonPie with a given model or prompt")
|
|
11
|
+
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")
|
|
12
|
+
parser.add_argument("-m", "--model", help="Model alias or full name", default=None)
|
|
13
|
+
parser.add_argument("-n", "--new", action="store_true", help="Start a new chat session")
|
|
14
|
+
parser.add_argument("-s", "--session", help="Load an existing session by ID")
|
|
15
|
+
parser.add_argument("-l", "--list", action="store_true", help="List chat sessions")
|
|
16
|
+
parser.add_argument("-d", "--delete", help="Delete a session by ID")
|
|
17
|
+
parser.add_argument("-t", "--title", help="Set or update session title")
|
|
18
|
+
parser.add_argument("-c", "--close", action="store_true", help="Close current session")
|
|
19
|
+
parser.add_argument("-p", "--print", action="store_true", help="Print current session history")
|
|
20
|
+
parser.add_argument("--delete-all", action="store_true", help="Delete all stored sessions")
|
|
21
|
+
parser.add_argument("prompt", nargs="*", help="Prompt text")
|
|
22
|
+
return parser
|
lemonpie/cli/ui.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import random
|
|
2
|
+
import sys
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from lemonpie.sessions.storage import list_sessions
|
|
7
|
+
|
|
8
|
+
CONNECTING_MSGS = [
|
|
9
|
+
"Connecting",
|
|
10
|
+
"Squeezing the lemons",
|
|
11
|
+
"Knocking on Ollama’s door",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
WAITING_MSGS = [
|
|
15
|
+
"Waiting for model response",
|
|
16
|
+
"The pie is cooking",
|
|
17
|
+
"Brewing tokens",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def confirm(prompt):
|
|
22
|
+
ans = input(f"{prompt} (y/N): ").strip().lower()
|
|
23
|
+
return ans in ("y", "yes")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def print_session(session):
|
|
27
|
+
print(f"Session {session['id']} — {session.get('title') or '<no title>'}")
|
|
28
|
+
for turn in session["history"]:
|
|
29
|
+
role = turn["role"]
|
|
30
|
+
content = turn["content"]
|
|
31
|
+
print(f"{role} [{turn.get('ts', '')}] : {content}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def print_sessions_list():
|
|
35
|
+
sessions = list_sessions()
|
|
36
|
+
if not sessions:
|
|
37
|
+
print("No sessions found.")
|
|
38
|
+
return
|
|
39
|
+
for sid, title, created, updated, is_current in sessions:
|
|
40
|
+
print(f"{is_current} {sid} {title} created: {created}, updated: {updated}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class StatusSpinner:
|
|
44
|
+
def __init__(self, messages, interval=0.5):
|
|
45
|
+
self.messages = messages
|
|
46
|
+
self.interval = interval
|
|
47
|
+
self.running = False
|
|
48
|
+
self.thread = None
|
|
49
|
+
|
|
50
|
+
def start(self):
|
|
51
|
+
self.running = True
|
|
52
|
+
self.thread = threading.Thread(target=self._animate, daemon=True)
|
|
53
|
+
self.thread.start()
|
|
54
|
+
|
|
55
|
+
def _animate(self):
|
|
56
|
+
dots = ""
|
|
57
|
+
msg = random.choice(self.messages)
|
|
58
|
+
while self.running:
|
|
59
|
+
dots = (dots + ".") if len(dots) < 3 else ""
|
|
60
|
+
sys.stdout.write("\r" + msg + dots + " ")
|
|
61
|
+
sys.stdout.flush()
|
|
62
|
+
time.sleep(self.interval)
|
|
63
|
+
|
|
64
|
+
def stop(self, clear=True, replace=None):
|
|
65
|
+
self.running = False
|
|
66
|
+
if self.thread:
|
|
67
|
+
self.thread.join()
|
|
68
|
+
if clear:
|
|
69
|
+
clear_len = max(len(m) + 6 for m in self.messages)
|
|
70
|
+
sys.stdout.write("\r" + " " * clear_len + "\r")
|
|
71
|
+
sys.stdout.flush()
|
|
72
|
+
if replace:
|
|
73
|
+
sys.stdout.write(replace + "\n")
|
|
74
|
+
sys.stdout.flush()
|