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/config.py ADDED
@@ -0,0 +1,68 @@
1
+ import json
2
+ import os
3
+ from urllib.parse import urlparse
4
+
5
+ import httpx
6
+
7
+ from lemonpie.paths import CONFIG_FILE
8
+
9
+
10
+ def save_config(cfg):
11
+ tmp = CONFIG_FILE + ".tmp"
12
+ with open(tmp, "w", encoding="utf-8") as f:
13
+ json.dump(cfg, f, indent=2, ensure_ascii=False)
14
+ os.replace(tmp, CONFIG_FILE)
15
+
16
+
17
+ def load_config():
18
+ if not os.path.exists(CONFIG_FILE):
19
+ # default structure uses list-of-objects for models
20
+ default_cfg = {
21
+ "server": "http://127.0.0.1:11434",
22
+ "default": None,
23
+ "models": [],
24
+ }
25
+ save_config(default_cfg)
26
+ return default_cfg
27
+
28
+ with open(CONFIG_FILE, "r", encoding="utf-8") as f:
29
+ cfg = json.load(f)
30
+
31
+ # Ensure structure keys exist
32
+ cfg.setdefault("server", None)
33
+ cfg.setdefault("default", None)
34
+ cfg.setdefault("models", [])
35
+ return cfg
36
+
37
+
38
+ def resolve_server_host(cfg):
39
+ return os.environ.get("OLLAMA_HOST") or cfg.get("server")
40
+
41
+
42
+ def is_valid_url(url):
43
+ try:
44
+ p = urlparse(url)
45
+ except (TypeError, AttributeError, ValueError):
46
+ return False
47
+
48
+ return p.scheme in ("http", "https") and bool(p.netloc)
49
+
50
+
51
+ def ensure_models_list(cfg):
52
+ if not isinstance(cfg.get("models"), list):
53
+ cfg["models"] = []
54
+
55
+
56
+ def config_file_path():
57
+ """Return the active config file path.
58
+
59
+ Accessing CONFIG_FILE through this function (rather than importing it
60
+ directly) lets callers stay in sync with monkeypatching done by the test
61
+ fixtures — they patch ``lemonpie.config.CONFIG_FILE``, so any code that
62
+ reads it at call-time sees the patched value automatically.
63
+ """
64
+ return CONFIG_FILE
65
+
66
+
67
+ def build_timeout():
68
+ return httpx.Timeout(connect=5.0, read=600.0, write=30.0, pool=5.0)
File without changes
@@ -0,0 +1,61 @@
1
+ import sys
2
+
3
+ from lemonpie.sessions.storage import save_session
4
+
5
+
6
+ def find_by_alias(cfg, alias):
7
+ for idx, m in enumerate(cfg.get("models", [])):
8
+ if m.get("alias") == alias:
9
+ return idx, m
10
+ return None, None
11
+
12
+
13
+ def find_by_name(cfg, name):
14
+ for idx, m in enumerate(cfg.get("models", [])):
15
+ if m.get("name") == name:
16
+ return idx, m
17
+ return None, None
18
+
19
+
20
+ def resolve_model(cfg, args_model, default_model_name):
21
+ if args_model:
22
+ _, alias_entry = find_by_alias(cfg, args_model)
23
+ if alias_entry:
24
+ return alias_entry["name"]
25
+ _, name_entry = find_by_name(cfg, args_model)
26
+ if name_entry:
27
+ return name_entry["name"]
28
+ return args_model
29
+ return default_model_name
30
+
31
+
32
+ def handle_model_switch(cfg, session, requested_model):
33
+ """
34
+ Handles validating a requested model/alias and updates the active session
35
+ if confirmed by the user.
36
+ """
37
+ if not session or not requested_model:
38
+ return session
39
+
40
+ _, alias_entry = find_by_alias(cfg, requested_model)
41
+ _, name_entry = find_by_name(cfg, requested_model)
42
+
43
+ if alias_entry:
44
+ new_model = alias_entry["name"]
45
+ elif name_entry:
46
+ new_model = name_entry["name"]
47
+ else:
48
+ print(f'Warning: "{requested_model}" is not a known alias or configured model.')
49
+ print('To add it, use lmConfig --add-model <alias> <model_name>')
50
+ sys.exit(0)
51
+
52
+ if new_model != session.get("model"):
53
+ confirm = input(f'Change session {session["id"]} model to "{new_model}"? (Y/n): ')
54
+ if confirm.lower() in ("y", "yes", ""):
55
+ session["model"] = new_model
56
+ save_session(session["id"], session)
57
+ print(f'Session model updated to {new_model}.')
58
+ else:
59
+ print("Aborted model change.")
60
+
61
+ return session
@@ -0,0 +1,49 @@
1
+ """Ollama API interaction abstractions: client construction and streaming chat."""
2
+
3
+ from ollama import Client
4
+
5
+
6
+ def build_client(server_host, timeout):
7
+ return Client(host=server_host, timeout=timeout)
8
+
9
+
10
+ def stream_chat(client, model, messages):
11
+ """
12
+ Stream a chat completion from Ollama, yielding text content chunks.
13
+
14
+ The underlying stream is closed automatically when this generator is
15
+ closed (e.g. via a `for` loop finishing, an exception propagating, or an
16
+ explicit `.close()` call on the generator by the caller).
17
+ """
18
+ stream = client.chat(model=model, messages=messages, stream=True)
19
+ try:
20
+ for chunk in stream:
21
+ # Standard Ollama client attribute access
22
+ content = getattr(getattr(chunk, "message", None), "content", None)
23
+ if content is None and isinstance(chunk, dict):
24
+ content = chunk.get("message", {}).get("content", "")
25
+ if content:
26
+ yield content
27
+ finally:
28
+ if hasattr(stream, "close"):
29
+ stream.close()
30
+
31
+
32
+ def resolve_ollama_error(exc, server_host):
33
+ """
34
+ Map an exception raised during an Ollama request to a (message, hint)
35
+ pair suitable for printing to the user. `hint` may be None.
36
+ """
37
+ msg = str(exc)
38
+ if "[Errno 111]" in msg or "Connection refused" in msg:
39
+ return (
40
+ "Ollama server did not respond: Connection refused.",
41
+ (f"Hint: Ollama may not be running, or it may not be listening on: {server_host}\n"
42
+ "Check that the server is started with `ollama serve` and bound to the correct interface."),
43
+ )
44
+ if "[Errno 110]" in msg or "timed out" in msg.lower():
45
+ return (
46
+ "Failed to contact Ollama server: Connection timed out.",
47
+ f"Hint: The server at {server_host} is unreachable. Verify IP/port and network.",
48
+ )
49
+ return (f"Failed to contact Ollama server: {msg}", None)
lemonpie/main.py ADDED
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ LemonPie (lm.py) — lightweight CLI for managing chat sessions with Ollama
4
+
5
+ Purpose
6
+ Manage chat sessions, send prompts to Ollama models, and persist session
7
+ history locally under `sessions/`. Configuration (host, default model, aliases)
8
+ is stored in `config.json`.
9
+
10
+ Quick usage
11
+ lm -n "Hello" # start a new session
12
+ lm "Hello" # send prompt (auto-creates if none)
13
+ lm -l # list sessions
14
+ lm -p # print current session
15
+ lm -h # full help and options
16
+
17
+ See README.md for details and maintainer notes.
18
+ """
19
+
20
+ import sys
21
+
22
+ from lemonpie.cli.parser import build_parser
23
+ from lemonpie.cli.ui import (
24
+ CONNECTING_MSGS,
25
+ StatusSpinner,
26
+ print_session,
27
+ print_sessions_list,
28
+ )
29
+ from lemonpie.config import (
30
+ build_timeout,
31
+ load_config,
32
+ resolve_server_host,
33
+ )
34
+ from lemonpie.engine.models import (
35
+ find_by_name,
36
+ handle_model_switch,
37
+ resolve_model,
38
+ )
39
+ from lemonpie.engine.ollama import (
40
+ build_client,
41
+ resolve_ollama_error,
42
+ stream_chat,
43
+ )
44
+ from lemonpie.sessions.storage import (
45
+ close_session,
46
+ delete_all_sessions,
47
+ delete_session_by_id,
48
+ load_session,
49
+ read_current,
50
+ resolve_session,
51
+ save_session,
52
+ update_title,
53
+ )
54
+ from lemonpie.time_utils import now_ts
55
+
56
+
57
+ def main():
58
+ cfg = load_config()
59
+ server_host = resolve_server_host(cfg)
60
+ timeout = build_timeout()
61
+ client = build_client(server_host, timeout)
62
+ default_model_name = cfg.get("default") or None
63
+ parser = build_parser()
64
+ args = parser.parse_args()
65
+
66
+ if len(sys.argv) == 1:
67
+ parser.print_help()
68
+ sys.exit(1)
69
+
70
+ current_id = read_current()
71
+
72
+ # Direct CLI actions
73
+
74
+ if args.list:
75
+ print_sessions_list(); sys.exit(0)
76
+
77
+ if args.print:
78
+ if not current_id:
79
+ print("No active session.")
80
+ sys.exit(0)
81
+ session = load_session(current_id)
82
+ if not session:
83
+ print(f"Session {current_id} not found.")
84
+ sys.exit(0)
85
+ print_session(session)
86
+ sys.exit(0)
87
+
88
+ if args.delete:
89
+ delete_session_by_id(args.delete); sys.exit(0)
90
+
91
+ if args.close:
92
+ close_session(); sys.exit(0)
93
+
94
+ if args.delete_all:
95
+ confirm = input("Are you sure you want to delete ALL sessions? (y/N): ")
96
+ if confirm.lower() in ("y", "yes"):
97
+ count = delete_all_sessions()
98
+ print(f"Deleted {count} session(s)."); sys.exit(0)
99
+ else:
100
+ print("Aborted."); sys.exit(0)
101
+
102
+ model_flag = args.model is not None
103
+ model = resolve_model(cfg, args.model, default_model_name)
104
+
105
+ if model is None:
106
+ print("No default model configured.")
107
+ print("Use lmConfig to add one or pass a known alias with -m.")
108
+ sys.exit(1)
109
+
110
+ if model_flag and not current_id and not args.new and not args.session and not args.prompt:
111
+ print(f'No current session.\n'
112
+ f'To create a new session with "{args.model}" use: lm -n -m {args.model}\n'
113
+ f'To change the model of a specific session: lm -s <id> -m {args.model}\n'
114
+ f'To change the default model use lmConfig.')
115
+ sys.exit(0)
116
+
117
+ session = resolve_session(args, model, current_id)
118
+ session_id = session["id"]
119
+
120
+ if model_flag and session:
121
+ session = handle_model_switch(cfg, session, args.model)
122
+
123
+ if args.title:
124
+ session = update_title(session, model, args.title, args.prompt)
125
+ if not args.prompt:
126
+ sys.exit(0)
127
+
128
+ if args.prompt:
129
+ user_prompt = " ".join(args.prompt)
130
+ turn_ts = now_ts()
131
+ session["history"].append({"role": "user", "content": user_prompt, "ts": turn_ts})
132
+ session["updated_at"] = turn_ts
133
+ save_session(session_id, session)
134
+
135
+ if not find_by_name(cfg, model):
136
+ print(f'Configured models do not include "{model}". Use lmConfig to add it or pass a known alias.')
137
+ sys.exit(1)
138
+
139
+ spinner = StatusSpinner(CONNECTING_MSGS)
140
+ spinner.start()
141
+
142
+ assistant_reply = ""
143
+ reply_ts = None
144
+ first_chunk_seen = False
145
+ chunks = stream_chat(client, model, session["history"])
146
+
147
+ try:
148
+ for content in chunks:
149
+ if not first_chunk_seen:
150
+ spinner.stop()
151
+ first_chunk_seen = True
152
+ print(content, end="", flush=True)
153
+ assistant_reply += content
154
+ print()
155
+ reply_ts = now_ts()
156
+
157
+ except KeyboardInterrupt:
158
+ chunks.close()
159
+ print("\nInterrupted by user.")
160
+ sys.exit(1)
161
+
162
+ except Exception as e:
163
+ title, hint = resolve_ollama_error(e, server_host)
164
+ print("\n" + title)
165
+ if hint:
166
+ print(hint)
167
+ sys.exit(1)
168
+
169
+ finally:
170
+ spinner.stop()
171
+
172
+ if assistant_reply:
173
+ session["history"].append({"role": "assistant", "content": assistant_reply, "ts": reply_ts or now_ts()})
174
+ session["updated_at"] = reply_ts or now_ts()
175
+ save_session(session_id, session)
176
+ else:
177
+ print("No response from model.")
178
+
179
+ if __name__ == "__main__":
180
+ main()
lemonpie/paths.py ADDED
@@ -0,0 +1,27 @@
1
+ import os
2
+
3
+ from platformdirs import user_config_dir, user_data_dir
4
+
5
+ APP_NAME = "lemonpie"
6
+
7
+ # Config directory: OS-appropriate user config location
8
+ # (~/.config/lemonpie, %LOCALAPPDATA%\lemonpie, ~/Library/Application Support/lemonpie).
9
+ # Override with $LEMONPIE_CONFIG_DIR.
10
+ CONFIG_DIR = os.environ.get(
11
+ "LEMONPIE_CONFIG_DIR",
12
+ user_config_dir(APP_NAME, appauthor=False)
13
+ )
14
+ os.makedirs(CONFIG_DIR, exist_ok=True)
15
+
16
+ CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
17
+
18
+ # Sessions directory: OS-appropriate user data location, with precedence given
19
+ # to $LEMONPIE_SESSIONS_DIR for backward compatibility / testing / containers.
20
+ DATA_DIR = user_data_dir(APP_NAME, appauthor=False)
21
+ SESSIONS_DIR = os.environ.get(
22
+ "LEMONPIE_SESSIONS_DIR",
23
+ os.path.join(DATA_DIR, "sessions")
24
+ )
25
+ os.makedirs(SESSIONS_DIR, exist_ok=True)
26
+
27
+ CURRENT_FILE = os.path.join(SESSIONS_DIR, ".current")
File without changes
@@ -0,0 +1,179 @@
1
+ import glob
2
+ import json
3
+ import os
4
+ import sys
5
+ import uuid
6
+ from datetime import datetime
7
+
8
+ from lemonpie.paths import CURRENT_FILE, SESSIONS_DIR
9
+ from lemonpie.time_utils import now_ts, short_date
10
+
11
+ MAX_TITLE_LEN = 50
12
+
13
+ def session_path(session_id):
14
+ return os.path.join(SESSIONS_DIR, f"{session_id}.json")
15
+
16
+ def read_current():
17
+ try:
18
+ with open(CURRENT_FILE, "r", encoding="utf-8") as f:
19
+ sid = f.read().strip()
20
+ return sid if sid else None
21
+ except FileNotFoundError:
22
+ return None
23
+
24
+ def write_current(session_id):
25
+ tmp = CURRENT_FILE + ".tmp"
26
+ with open(tmp, "w", encoding="utf-8") as f:
27
+ f.write(session_id)
28
+ os.replace(tmp, CURRENT_FILE)
29
+
30
+ def clear_current():
31
+ try:
32
+ os.remove(CURRENT_FILE)
33
+ except FileNotFoundError:
34
+ pass
35
+
36
+ def resolve_session(args, model, current_id):
37
+ if args.new:
38
+ return create_session(args.prompt, model)
39
+ if args.session:
40
+ return load_session_by_id(args.session, model)
41
+ if current_id:
42
+ return load_session(current_id)
43
+ return create_session(args.prompt, model)
44
+
45
+ def load_session(session_id):
46
+ try:
47
+ with open(session_path(session_id), "r", encoding="utf-8") as f:
48
+ s = json.load(f)
49
+ # Backfill created_at/updated_at from history if missing
50
+ if "created_at" not in s or not s.get("created_at"):
51
+ if s.get("history"):
52
+ s["created_at"] = s["history"][0].get("ts")
53
+ else:
54
+ # fallback to file mtime
55
+ s["created_at"] = datetime.fromtimestamp(
56
+ os.path.getmtime(session_path(session_id))
57
+ ).astimezone().isoformat()
58
+ if "updated_at" not in s or not s.get("updated_at"):
59
+ if s.get("history"):
60
+ s["updated_at"] = s["history"][-1].get("ts")
61
+ else:
62
+ s["updated_at"] = s["created_at"]
63
+ return s
64
+ except FileNotFoundError:
65
+ return {"id": session_id, "title": None, "history": [], "created_at": None, "updated_at": None}
66
+
67
+ def save_session(session_id, session):
68
+ tmp = session_path(session_id) + ".tmp"
69
+ with open(tmp, "w", encoding="utf-8") as f:
70
+ json.dump(session, f, indent=2)
71
+ os.replace(tmp, session_path(session_id))
72
+
73
+ def delete_session(session_id):
74
+ try:
75
+ os.remove(session_path(session_id))
76
+ return True
77
+ except FileNotFoundError:
78
+ return False
79
+
80
+ def delete_all_sessions():
81
+ """Deletes all session files in SESSIONS_DIR and clears current session marker."""
82
+ deleted_count = 0
83
+
84
+ if os.path.exists(SESSIONS_DIR):
85
+ for filepath in glob.glob(os.path.join(SESSIONS_DIR, "*.json")):
86
+ try:
87
+ os.remove(filepath)
88
+ deleted_count += 1
89
+ except OSError:
90
+ pass
91
+
92
+ clear_current()
93
+ return deleted_count
94
+
95
+ def default_title(prompt):
96
+ return prompt if len(prompt) <= MAX_TITLE_LEN else prompt[:MAX_TITLE_LEN].rstrip() + "…"
97
+
98
+ def set_title(session, new_title):
99
+ if len(new_title) > MAX_TITLE_LEN:
100
+ print(f"title exceeds {MAX_TITLE_LEN} characters. please try again")
101
+ return False
102
+ session["title"] = new_title
103
+ save_session(session["id"], session)
104
+ return True
105
+
106
+ def create_session(prompt, model, title=None):
107
+ session_id = datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:6]
108
+ if title is None:
109
+ title = default_title(" ".join(prompt)) if prompt else "<no title>"
110
+ ts = now_ts()
111
+ session = {"id": session_id, "model": model, "title": title, "history": [], "created_at": ts, "updated_at": ts}
112
+ save_session(session_id, session)
113
+ write_current(session_id)
114
+ return session
115
+
116
+ def load_session_by_id(session_id, model=None):
117
+ """Load a session by ID and set it as current."""
118
+ session = load_session(session_id)
119
+ if model:
120
+ session["model"] = model
121
+ write_current(session_id)
122
+ return session
123
+
124
+ def delete_session_by_id(session_id):
125
+ """Delete a session after user confirmation."""
126
+ confirm = input(f'Delete session {session_id}? (Y/n): ')
127
+ if confirm.lower() in ("y", "yes", ""):
128
+ if delete_session(session_id):
129
+ print(f"Deleted session {session_id}")
130
+ if read_current() == session_id:
131
+ clear_current()
132
+ else:
133
+ print(f"No session found with id {session_id}")
134
+ else:
135
+ print("Aborted deletion.")
136
+
137
+ def close_session():
138
+ """Close the current session pointer."""
139
+ clear_current()
140
+ print("Current session closed.")
141
+
142
+ def update_title(session, model, new_title, prompt=None):
143
+ """Update or create a session with a new title."""
144
+ if not session:
145
+ confirm = input(f'No current session. Create a new session with title "{new_title}"? (Y/n): ')
146
+ if confirm.lower() in ("y", "yes", ""):
147
+ session = create_session(prompt or [], model, title=new_title)
148
+ print(f'Created new session {session["id"]} with title "{new_title}".')
149
+ else:
150
+ print("Aborted creating new session.")
151
+ sys.exit(0)
152
+ else:
153
+ set_title(session, new_title)
154
+ print(f'Updated title for session {session["id"]} to "{new_title}".')
155
+
156
+ # If no prompt was passed, exit after title update
157
+ if not prompt:
158
+ sys.exit(0)
159
+
160
+ return session
161
+
162
+ def list_sessions():
163
+ sessions = []
164
+ current = read_current()
165
+ for fname in os.listdir(SESSIONS_DIR):
166
+ if not fname.endswith(".json"):
167
+ continue
168
+ try:
169
+ with open(os.path.join(SESSIONS_DIR, fname), encoding="utf-8") as f:
170
+ data = json.load(f)
171
+ if "id" in data:
172
+ created = short_date(data.get("created_at"))
173
+ updated = short_date(data.get("updated_at"))
174
+ is_current = "*" if data["id"] == current else " "
175
+ sessions.append((data["id"], data.get("title") or "<no title>", created, updated, is_current))
176
+ except Exception:
177
+ # skip invalid JSON files
178
+ continue
179
+ return sessions
lemonpie/time_utils.py ADDED
@@ -0,0 +1,14 @@
1
+ from datetime import UTC, datetime
2
+
3
+
4
+ def now_ts():
5
+ return datetime.now(UTC).astimezone().isoformat()
6
+
7
+ def short_date(iso_ts):
8
+ if not iso_ts:
9
+ return "<unknown>"
10
+ try:
11
+ dt: datetime = datetime.fromisoformat(iso_ts)
12
+ return dt.strftime("%Y-%m-%d")
13
+ except Exception:
14
+ return iso_ts