lupaxa-basic-cli-chatbot 0.1.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.
- lupaxa/basic_cli_chatbot/__init__.py +10 -0
- lupaxa/basic_cli_chatbot/__main__.py +8 -0
- lupaxa/basic_cli_chatbot/chat.py +71 -0
- lupaxa/basic_cli_chatbot/cli.py +624 -0
- lupaxa/basic_cli_chatbot/config.py +210 -0
- lupaxa/basic_cli_chatbot/providers/__init__.py +34 -0
- lupaxa/basic_cli_chatbot/providers/base.py +35 -0
- lupaxa/basic_cli_chatbot/providers/catalog.py +41 -0
- lupaxa/basic_cli_chatbot/providers/errors.py +21 -0
- lupaxa/basic_cli_chatbot/providers/gemini.py +131 -0
- lupaxa/basic_cli_chatbot/providers/grok.py +140 -0
- lupaxa/basic_cli_chatbot/providers/ollama.py +108 -0
- lupaxa/basic_cli_chatbot/providers/openai.py +129 -0
- lupaxa/basic_cli_chatbot/version.py +10 -0
- lupaxa_basic_cli_chatbot-0.1.0.dist-info/METADATA +168 -0
- lupaxa_basic_cli_chatbot-0.1.0.dist-info/RECORD +19 -0
- lupaxa_basic_cli_chatbot-0.1.0.dist-info/WHEEL +4 -0
- lupaxa_basic_cli_chatbot-0.1.0.dist-info/entry_points.txt +2 -0
- lupaxa_basic_cli_chatbot-0.1.0.dist-info/licenses/LICENCE +21 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Conversation history helper. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .providers.base import Provider
|
|
6
|
+
|
|
7
|
+
SYSTEM_PROMPT = (
|
|
8
|
+
"You are a helpful general-purpose assistant. Answer questions clearly and concisely."
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def trim(conversation: list[dict[str, str]], max_context_messages: int) -> None:
|
|
13
|
+
"""Drop oldest complete user/assistant pairs until the list fits.
|
|
14
|
+
|
|
15
|
+
``0`` means unlimited. An odd cap uses the next lower even number.
|
|
16
|
+
A trailing user row with no assistant reply is kept.
|
|
17
|
+
"""
|
|
18
|
+
if max_context_messages == 0:
|
|
19
|
+
return
|
|
20
|
+
limit = max_context_messages - (max_context_messages % 2)
|
|
21
|
+
while len(conversation) > limit:
|
|
22
|
+
complete_pair = (
|
|
23
|
+
len(conversation) >= 2
|
|
24
|
+
and conversation[0].get("role") == "user"
|
|
25
|
+
and conversation[1].get("role") == "assistant"
|
|
26
|
+
)
|
|
27
|
+
if not complete_pair:
|
|
28
|
+
break
|
|
29
|
+
if conversation[-1].get("role") == "user" and len(conversation) < 3:
|
|
30
|
+
break
|
|
31
|
+
del conversation[:2]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def begin_turn(
|
|
35
|
+
question: str,
|
|
36
|
+
conversation: list[dict[str, str]],
|
|
37
|
+
max_context_messages: int,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""Append the user row, then trim."""
|
|
40
|
+
conversation.append({"role": "user", "content": question})
|
|
41
|
+
trim(conversation, max_context_messages)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def finish_turn(conversation: list[dict[str, str]], answer: str) -> None:
|
|
45
|
+
"""Append the assistant row."""
|
|
46
|
+
conversation.append({"role": "assistant", "content": answer})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def fail_turn(conversation: list[dict[str, str]]) -> None:
|
|
50
|
+
"""Remove the trailing user row after a failed request."""
|
|
51
|
+
if conversation and conversation[-1].get("role") == "user":
|
|
52
|
+
conversation.pop()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ask(
|
|
56
|
+
question: str,
|
|
57
|
+
conversation: list[dict[str, str]],
|
|
58
|
+
provider: Provider,
|
|
59
|
+
model: str,
|
|
60
|
+
*,
|
|
61
|
+
max_context_messages: int,
|
|
62
|
+
) -> str:
|
|
63
|
+
"""Append one user turn, request a reply, and append that reply."""
|
|
64
|
+
begin_turn(question, conversation, max_context_messages)
|
|
65
|
+
try:
|
|
66
|
+
answer = provider.chat(list(conversation), model, SYSTEM_PROMPT)
|
|
67
|
+
except Exception:
|
|
68
|
+
fail_turn(conversation)
|
|
69
|
+
raise
|
|
70
|
+
finish_turn(conversation, answer)
|
|
71
|
+
return answer
|
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
"""Command-line interface for basic-cli-chatbot."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .chat import (
|
|
12
|
+
SYSTEM_PROMPT,
|
|
13
|
+
ask,
|
|
14
|
+
begin_turn,
|
|
15
|
+
fail_turn,
|
|
16
|
+
finish_turn,
|
|
17
|
+
)
|
|
18
|
+
from .config import ConfigError, ConfigFile, default_config_path, find_profile, load_config
|
|
19
|
+
from .providers import KNOWN, Provider, build
|
|
20
|
+
from .providers.catalog import CATALOG, gemini_timeout_ms
|
|
21
|
+
from .providers.errors import ChatError
|
|
22
|
+
from .version import __version__
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
26
|
+
parser = argparse.ArgumentParser(description="A simple command-line AI chatbot.")
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"--provider",
|
|
29
|
+
help="Chat provider: openai, gemini, grok, or ollama.",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument("--model", help="Model name for the selected provider.")
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"--config",
|
|
34
|
+
help="Profile file. Defaults to the user config path.",
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--profile",
|
|
38
|
+
help="Profile name from the config file.",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"--ollama-host",
|
|
42
|
+
default=None,
|
|
43
|
+
help="Ollama server URL (default: http://localhost:11434).",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--max-context-messages",
|
|
47
|
+
type=int,
|
|
48
|
+
default=None,
|
|
49
|
+
help="Maximum user and assistant rows to keep. 0 means unlimited.",
|
|
50
|
+
)
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"--timeout",
|
|
53
|
+
type=float,
|
|
54
|
+
default=None,
|
|
55
|
+
help="Reply timeout in seconds.",
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--show-config",
|
|
59
|
+
action="store_true",
|
|
60
|
+
help="Print the effective settings and exit.",
|
|
61
|
+
)
|
|
62
|
+
parser.add_argument(
|
|
63
|
+
"--validate",
|
|
64
|
+
action="store_true",
|
|
65
|
+
help="Check the config file and exit.",
|
|
66
|
+
)
|
|
67
|
+
parser.add_argument(
|
|
68
|
+
"--list-models",
|
|
69
|
+
action="store_true",
|
|
70
|
+
help="List model names for the selected provider and exit.",
|
|
71
|
+
)
|
|
72
|
+
parser.add_argument(
|
|
73
|
+
"--stream",
|
|
74
|
+
action="store_true",
|
|
75
|
+
help="Stream the reply as it arrives (default).",
|
|
76
|
+
)
|
|
77
|
+
parser.add_argument(
|
|
78
|
+
"--no-stream",
|
|
79
|
+
action="store_true",
|
|
80
|
+
help="Print the reply in one piece.",
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--version",
|
|
84
|
+
action="store_true",
|
|
85
|
+
help="Show version information and exit.",
|
|
86
|
+
)
|
|
87
|
+
parser.add_argument("question", nargs="?", help="Ask one question and exit.")
|
|
88
|
+
return parser
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _flag_or_env(flag: str | None, env_name: str) -> str | None:
|
|
92
|
+
if flag is not None:
|
|
93
|
+
text = flag.strip()
|
|
94
|
+
else:
|
|
95
|
+
raw = os.environ.get(env_name)
|
|
96
|
+
if raw is None:
|
|
97
|
+
return None
|
|
98
|
+
text = raw.strip()
|
|
99
|
+
if not text:
|
|
100
|
+
return None
|
|
101
|
+
return text
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _resolve_provider(flag: str | None) -> str | None:
|
|
105
|
+
text = _flag_or_env(flag, "BASIC_CLI_CHATBOT_PROVIDER")
|
|
106
|
+
if text is None:
|
|
107
|
+
return None
|
|
108
|
+
return text.casefold()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _resolve_model(flag: str | None) -> str | None:
|
|
112
|
+
return _flag_or_env(flag, "BASIC_CLI_CHATBOT_MODEL")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _env_timeout() -> float | None:
|
|
116
|
+
raw = os.environ.get("BASIC_CLI_CHATBOT_TIMEOUT")
|
|
117
|
+
if raw is None:
|
|
118
|
+
return None
|
|
119
|
+
text = raw.strip()
|
|
120
|
+
message = "BASIC_CLI_CHATBOT_TIMEOUT must be a number of seconds greater than 0"
|
|
121
|
+
if not text:
|
|
122
|
+
raise ConfigError(message)
|
|
123
|
+
try:
|
|
124
|
+
value = float(text)
|
|
125
|
+
except ValueError:
|
|
126
|
+
raise ConfigError(message) from None
|
|
127
|
+
if not math.isfinite(value) or value <= 0:
|
|
128
|
+
raise ConfigError(message)
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _resolve_timeout(
|
|
133
|
+
flag: float | None,
|
|
134
|
+
profile_value: float | None,
|
|
135
|
+
provider_name: str | None,
|
|
136
|
+
) -> float | None:
|
|
137
|
+
if flag is not None:
|
|
138
|
+
return flag
|
|
139
|
+
if profile_value is not None:
|
|
140
|
+
return profile_value
|
|
141
|
+
chosen = _env_timeout()
|
|
142
|
+
if chosen is not None:
|
|
143
|
+
return chosen
|
|
144
|
+
if provider_name is None or provider_name not in CATALOG:
|
|
145
|
+
return None
|
|
146
|
+
return float(CATALOG[provider_name].timeout_seconds)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _format_timeout(timeout: float | None) -> str:
|
|
150
|
+
if timeout is None:
|
|
151
|
+
return "not set"
|
|
152
|
+
if timeout.is_integer():
|
|
153
|
+
return str(int(timeout))
|
|
154
|
+
text = format(timeout, "f").rstrip("0").rstrip(".")
|
|
155
|
+
return text
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _reject_gemini_timeout(provider_name: str, timeout: float) -> bool:
|
|
159
|
+
if provider_name != "gemini":
|
|
160
|
+
return False
|
|
161
|
+
try:
|
|
162
|
+
gemini_timeout_ms(timeout)
|
|
163
|
+
except ValueError as exc:
|
|
164
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
165
|
+
return True
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def format_show_config(
|
|
170
|
+
provider: str | None,
|
|
171
|
+
model: str | None,
|
|
172
|
+
max_context_messages: int,
|
|
173
|
+
ollama_host: str,
|
|
174
|
+
timeout: float | None,
|
|
175
|
+
profile: str | None = None,
|
|
176
|
+
config_path: Path | None = None,
|
|
177
|
+
) -> None:
|
|
178
|
+
"""Print the effective settings. Never print a secret."""
|
|
179
|
+
facts = CATALOG.get(provider) if provider is not None else None
|
|
180
|
+
lines = [
|
|
181
|
+
f"provider: {provider or 'not set'}",
|
|
182
|
+
f"model: {model or 'not set'}",
|
|
183
|
+
f"mode: {facts.mode if facts is not None else 'not set'}",
|
|
184
|
+
f"max-context-messages: {max_context_messages}",
|
|
185
|
+
f"timeout: {_format_timeout(timeout)}",
|
|
186
|
+
]
|
|
187
|
+
if provider == "ollama":
|
|
188
|
+
lines.append(f"ollama-host: {ollama_host}")
|
|
189
|
+
if facts is not None and facts.api_key_env is not None:
|
|
190
|
+
state = "configured" if os.environ.get(facts.api_key_env) else "not configured"
|
|
191
|
+
lines.append(f"api-key: {state}")
|
|
192
|
+
if profile is not None and config_path is not None:
|
|
193
|
+
lines.append(f"profile: {profile}")
|
|
194
|
+
lines.append(f"config: {config_path}")
|
|
195
|
+
print("\n".join(lines))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
_STREAM_NOTICE = "Streaming is unavailable; using a single response."
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _print_stream_notice(*, interactive: bool) -> None:
|
|
202
|
+
print(_STREAM_NOTICE, file=sys.stdout if interactive else sys.stderr)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _print_reply(answer: str, *, interactive: bool) -> None:
|
|
206
|
+
if interactive:
|
|
207
|
+
print(f"\nAI: {answer}\n")
|
|
208
|
+
else:
|
|
209
|
+
print(answer)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _close_stream(text: str, *, interactive: bool) -> None:
|
|
213
|
+
if not text.endswith("\n"):
|
|
214
|
+
print(flush=True)
|
|
215
|
+
if interactive:
|
|
216
|
+
print(flush=True)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _collect_stream(
|
|
220
|
+
conversation: list[dict[str, str]],
|
|
221
|
+
provider: Provider,
|
|
222
|
+
model: str,
|
|
223
|
+
*,
|
|
224
|
+
interactive: bool,
|
|
225
|
+
) -> tuple[str, bool]:
|
|
226
|
+
"""Return the reply and whether its text was already written."""
|
|
227
|
+
if not provider.supports_stream:
|
|
228
|
+
_print_stream_notice(interactive=interactive)
|
|
229
|
+
return provider.chat(list(conversation), model, SYSTEM_PROMPT), False
|
|
230
|
+
|
|
231
|
+
parts: list[str] = []
|
|
232
|
+
try:
|
|
233
|
+
for delta in provider.stream(list(conversation), model, SYSTEM_PROMPT):
|
|
234
|
+
if interactive and not parts:
|
|
235
|
+
print("\nAI: ", end="", flush=True)
|
|
236
|
+
print(delta, end="", flush=True)
|
|
237
|
+
parts.append(delta)
|
|
238
|
+
except Exception:
|
|
239
|
+
if parts:
|
|
240
|
+
raise
|
|
241
|
+
_print_stream_notice(interactive=interactive)
|
|
242
|
+
return provider.chat(list(conversation), model, SYSTEM_PROMPT), False
|
|
243
|
+
|
|
244
|
+
if not parts:
|
|
245
|
+
raise ChatError("the provider returned an invalid response")
|
|
246
|
+
text = "".join(parts)
|
|
247
|
+
_close_stream(text, interactive=interactive)
|
|
248
|
+
return text, True
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _stream_reply(
|
|
252
|
+
question: str,
|
|
253
|
+
conversation: list[dict[str, str]],
|
|
254
|
+
provider: Provider,
|
|
255
|
+
model: str,
|
|
256
|
+
max_context_messages: int,
|
|
257
|
+
*,
|
|
258
|
+
interactive: bool,
|
|
259
|
+
) -> None:
|
|
260
|
+
begin_turn(question, conversation, max_context_messages)
|
|
261
|
+
try:
|
|
262
|
+
answer, streamed = _collect_stream(
|
|
263
|
+
conversation,
|
|
264
|
+
provider,
|
|
265
|
+
model,
|
|
266
|
+
interactive=interactive,
|
|
267
|
+
)
|
|
268
|
+
except Exception:
|
|
269
|
+
fail_turn(conversation)
|
|
270
|
+
raise
|
|
271
|
+
finish_turn(conversation, answer)
|
|
272
|
+
if not streamed:
|
|
273
|
+
_print_reply(answer, interactive=interactive)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def run_oneshot(
|
|
277
|
+
question: str,
|
|
278
|
+
provider_name: str,
|
|
279
|
+
model: str,
|
|
280
|
+
ollama_host: str,
|
|
281
|
+
max_context_messages: int,
|
|
282
|
+
*,
|
|
283
|
+
stream: bool,
|
|
284
|
+
timeout: float,
|
|
285
|
+
) -> int:
|
|
286
|
+
stripped = question.strip()
|
|
287
|
+
if not stripped:
|
|
288
|
+
print("Error: question is empty", file=sys.stderr)
|
|
289
|
+
return 2
|
|
290
|
+
try:
|
|
291
|
+
provider = build(provider_name, ollama_host=ollama_host, timeout=timeout)
|
|
292
|
+
if stream:
|
|
293
|
+
_stream_reply(
|
|
294
|
+
stripped,
|
|
295
|
+
[],
|
|
296
|
+
provider,
|
|
297
|
+
model,
|
|
298
|
+
max_context_messages,
|
|
299
|
+
interactive=False,
|
|
300
|
+
)
|
|
301
|
+
else:
|
|
302
|
+
answer = ask(
|
|
303
|
+
stripped,
|
|
304
|
+
[],
|
|
305
|
+
provider,
|
|
306
|
+
model,
|
|
307
|
+
max_context_messages=max_context_messages,
|
|
308
|
+
)
|
|
309
|
+
print(answer)
|
|
310
|
+
except KeyboardInterrupt:
|
|
311
|
+
print("\nGoodbye!")
|
|
312
|
+
return 0
|
|
313
|
+
except Exception as exc:
|
|
314
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
315
|
+
return 1
|
|
316
|
+
return 0
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def run_list_models(provider_name: str, ollama_host: str, *, timeout: float) -> int:
|
|
320
|
+
try:
|
|
321
|
+
provider = build(provider_name, ollama_host=ollama_host, timeout=timeout)
|
|
322
|
+
names = provider.list_models()
|
|
323
|
+
except KeyboardInterrupt:
|
|
324
|
+
print("\nGoodbye!")
|
|
325
|
+
return 0
|
|
326
|
+
except Exception as exc:
|
|
327
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
328
|
+
return 1
|
|
329
|
+
for name in names:
|
|
330
|
+
print(name)
|
|
331
|
+
return 0
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _print_slash(
|
|
335
|
+
command: str,
|
|
336
|
+
*,
|
|
337
|
+
provider_name: str,
|
|
338
|
+
model: str,
|
|
339
|
+
conversation: list[dict[str, str]],
|
|
340
|
+
max_context_messages: int,
|
|
341
|
+
) -> bool:
|
|
342
|
+
if command == "/context":
|
|
343
|
+
limit = "unlimited" if max_context_messages == 0 else str(max_context_messages)
|
|
344
|
+
print(f"context: {len(conversation)} messages, limit {limit}")
|
|
345
|
+
return True
|
|
346
|
+
if command == "/provider":
|
|
347
|
+
print(f"provider: {provider_name}")
|
|
348
|
+
return True
|
|
349
|
+
if command == "/model":
|
|
350
|
+
print(f"model: {model}")
|
|
351
|
+
return True
|
|
352
|
+
return False
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def run_interactive(
|
|
356
|
+
provider_name: str,
|
|
357
|
+
model: str,
|
|
358
|
+
ollama_host: str,
|
|
359
|
+
max_context_messages: int,
|
|
360
|
+
*,
|
|
361
|
+
stream: bool,
|
|
362
|
+
timeout: float,
|
|
363
|
+
) -> int:
|
|
364
|
+
mode = CATALOG[provider_name].mode
|
|
365
|
+
print("Simple AI Chatbot")
|
|
366
|
+
print(f"Provider: {provider_name}")
|
|
367
|
+
print(f"Model: {model}")
|
|
368
|
+
print(f"Mode: {mode}")
|
|
369
|
+
print("Type 'exit' or 'quit' to stop.")
|
|
370
|
+
print("Type 'clear' to clear the conversation context.\n")
|
|
371
|
+
conversation: list[dict[str, str]] = []
|
|
372
|
+
provider: Provider | None = None
|
|
373
|
+
while True:
|
|
374
|
+
try:
|
|
375
|
+
question = input("You: ").strip()
|
|
376
|
+
except (EOFError, KeyboardInterrupt):
|
|
377
|
+
print("\nGoodbye!")
|
|
378
|
+
return 0
|
|
379
|
+
if not question:
|
|
380
|
+
continue
|
|
381
|
+
command = question.casefold()
|
|
382
|
+
if command in {"exit", "quit"}:
|
|
383
|
+
print("Goodbye!")
|
|
384
|
+
return 0
|
|
385
|
+
if command == "clear":
|
|
386
|
+
conversation.clear()
|
|
387
|
+
print("\nConversation context cleared.\n")
|
|
388
|
+
continue
|
|
389
|
+
if _print_slash(
|
|
390
|
+
command,
|
|
391
|
+
provider_name=provider_name,
|
|
392
|
+
model=model,
|
|
393
|
+
conversation=conversation,
|
|
394
|
+
max_context_messages=max_context_messages,
|
|
395
|
+
):
|
|
396
|
+
continue
|
|
397
|
+
if provider is None:
|
|
398
|
+
try:
|
|
399
|
+
provider = build(provider_name, ollama_host=ollama_host, timeout=timeout)
|
|
400
|
+
except KeyboardInterrupt:
|
|
401
|
+
print("\nGoodbye!")
|
|
402
|
+
return 0
|
|
403
|
+
except Exception as exc:
|
|
404
|
+
print(f"\nError: {exc}\n")
|
|
405
|
+
continue
|
|
406
|
+
try:
|
|
407
|
+
if stream:
|
|
408
|
+
_stream_reply(
|
|
409
|
+
question,
|
|
410
|
+
conversation,
|
|
411
|
+
provider,
|
|
412
|
+
model,
|
|
413
|
+
max_context_messages,
|
|
414
|
+
interactive=True,
|
|
415
|
+
)
|
|
416
|
+
else:
|
|
417
|
+
answer = ask(
|
|
418
|
+
question,
|
|
419
|
+
conversation,
|
|
420
|
+
provider,
|
|
421
|
+
model,
|
|
422
|
+
max_context_messages=max_context_messages,
|
|
423
|
+
)
|
|
424
|
+
print(f"\nAI: {answer}\n")
|
|
425
|
+
except KeyboardInterrupt:
|
|
426
|
+
print("\nGoodbye!")
|
|
427
|
+
return 0
|
|
428
|
+
except Exception as exc:
|
|
429
|
+
print(f"\nError: {exc}\n")
|
|
430
|
+
continue
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
_HOST = "http://localhost:11434"
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _config_path(flag: str | None) -> tuple[Path, bool]:
|
|
437
|
+
if flag is not None:
|
|
438
|
+
return Path(flag).expanduser(), True
|
|
439
|
+
return default_config_path(), False
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _load_for_default(path: Path, explicit: bool) -> ConfigFile | None:
|
|
443
|
+
try:
|
|
444
|
+
return load_config(path)
|
|
445
|
+
except ConfigError as exc:
|
|
446
|
+
if not explicit and str(exc) == f"config file not found: {path}":
|
|
447
|
+
return None
|
|
448
|
+
raise
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _optional_host(flag: str | None, profile_value: str | None) -> str:
|
|
452
|
+
if flag is not None:
|
|
453
|
+
return flag
|
|
454
|
+
if profile_value is not None:
|
|
455
|
+
return profile_value
|
|
456
|
+
return _HOST
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _optional_limit(flag: int | None, profile_value: int | None) -> int:
|
|
460
|
+
if flag is not None:
|
|
461
|
+
return flag
|
|
462
|
+
if profile_value is not None:
|
|
463
|
+
return profile_value
|
|
464
|
+
return 0
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _stream_choice(stream: bool, no_stream: bool, profile_stream: bool | None) -> bool:
|
|
468
|
+
if stream:
|
|
469
|
+
return True
|
|
470
|
+
if no_stream:
|
|
471
|
+
return False
|
|
472
|
+
if profile_stream is not None:
|
|
473
|
+
return profile_stream
|
|
474
|
+
return True
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def main(argv: list[str] | None = None) -> int:
|
|
478
|
+
parser = build_parser()
|
|
479
|
+
args = parser.parse_args(argv)
|
|
480
|
+
if args.version:
|
|
481
|
+
print(f"basic-cli-chatbot {__version__}")
|
|
482
|
+
return 0
|
|
483
|
+
try:
|
|
484
|
+
return _run(args)
|
|
485
|
+
except ConfigError as exc:
|
|
486
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
487
|
+
return 2
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _run(args: argparse.Namespace) -> int:
|
|
491
|
+
choices = (args.question is not None, args.list_models, args.show_config, args.validate)
|
|
492
|
+
if sum(choices) > 1:
|
|
493
|
+
print(
|
|
494
|
+
"Error: choose one of a question, --list-models, --show-config, or --validate",
|
|
495
|
+
file=sys.stderr,
|
|
496
|
+
)
|
|
497
|
+
return 2
|
|
498
|
+
if (args.stream or args.no_stream) and (args.list_models or args.show_config or args.validate):
|
|
499
|
+
print("Error: --stream applies only to a chat", file=sys.stderr)
|
|
500
|
+
return 2
|
|
501
|
+
if args.stream and args.no_stream:
|
|
502
|
+
print("Error: --stream cannot be combined with --no-stream", file=sys.stderr)
|
|
503
|
+
return 2
|
|
504
|
+
if args.max_context_messages is not None and args.max_context_messages < 0:
|
|
505
|
+
print("Error: --max-context-messages must be 0 or greater", file=sys.stderr)
|
|
506
|
+
return 2
|
|
507
|
+
if args.timeout is not None and (not math.isfinite(args.timeout) or args.timeout <= 0):
|
|
508
|
+
print(
|
|
509
|
+
"Error: --timeout must be a number of seconds greater than 0",
|
|
510
|
+
file=sys.stderr,
|
|
511
|
+
)
|
|
512
|
+
return 2
|
|
513
|
+
if args.validate and (
|
|
514
|
+
args.profile is not None or args.provider is not None or args.model is not None
|
|
515
|
+
):
|
|
516
|
+
print(
|
|
517
|
+
"Error: --validate cannot be combined with --profile, --provider, or --model",
|
|
518
|
+
file=sys.stderr,
|
|
519
|
+
)
|
|
520
|
+
return 2
|
|
521
|
+
if args.profile is not None and (args.provider is not None or args.model is not None):
|
|
522
|
+
print("Error: --profile cannot be combined with --provider or --model", file=sys.stderr)
|
|
523
|
+
return 2
|
|
524
|
+
if args.profile is not None and not args.profile.strip():
|
|
525
|
+
print("Error: profile is required", file=sys.stderr)
|
|
526
|
+
return 2
|
|
527
|
+
|
|
528
|
+
path, explicit = _config_path(args.config)
|
|
529
|
+
profile = None
|
|
530
|
+
config_path: Path | None = None
|
|
531
|
+
provider_name: str | None
|
|
532
|
+
model: str | None
|
|
533
|
+
if args.validate:
|
|
534
|
+
loaded = load_config(path)
|
|
535
|
+
names = ", ".join(item.name for item in loaded.profiles)
|
|
536
|
+
second = f"profiles: {names}" if names else "profiles:"
|
|
537
|
+
print(f"config: ok\n{second}")
|
|
538
|
+
return 0
|
|
539
|
+
if args.profile is not None:
|
|
540
|
+
loaded = load_config(path)
|
|
541
|
+
profile = find_profile(loaded, args.profile)
|
|
542
|
+
config_path = path
|
|
543
|
+
provider_name = profile.provider
|
|
544
|
+
model = profile.model
|
|
545
|
+
elif args.provider is None and args.model is None:
|
|
546
|
+
default_file = _load_for_default(path, explicit)
|
|
547
|
+
if default_file is not None:
|
|
548
|
+
matches = [item for item in default_file.profiles if item.name.casefold() == "default"]
|
|
549
|
+
if matches:
|
|
550
|
+
profile = matches[0]
|
|
551
|
+
config_path = path
|
|
552
|
+
provider_name = profile.provider
|
|
553
|
+
model = profile.model
|
|
554
|
+
else:
|
|
555
|
+
provider_name = _resolve_provider(None)
|
|
556
|
+
model = _resolve_model(None)
|
|
557
|
+
else:
|
|
558
|
+
provider_name = _resolve_provider(None)
|
|
559
|
+
model = _resolve_model(None)
|
|
560
|
+
else:
|
|
561
|
+
provider_name = _resolve_provider(args.provider)
|
|
562
|
+
model = _resolve_model(args.model)
|
|
563
|
+
|
|
564
|
+
if profile is None:
|
|
565
|
+
ollama_host = args.ollama_host if args.ollama_host is not None else _HOST
|
|
566
|
+
max_context = 0 if args.max_context_messages is None else args.max_context_messages
|
|
567
|
+
stream = _stream_choice(args.stream, args.no_stream, None)
|
|
568
|
+
else:
|
|
569
|
+
ollama_host = _optional_host(args.ollama_host, profile.ollama_host)
|
|
570
|
+
max_context = _optional_limit(args.max_context_messages, profile.max_context_messages)
|
|
571
|
+
stream = _stream_choice(args.stream, args.no_stream, profile.stream)
|
|
572
|
+
|
|
573
|
+
profile_timeout = None if profile is None else profile.timeout
|
|
574
|
+
timeout = _resolve_timeout(args.timeout, profile_timeout, provider_name)
|
|
575
|
+
|
|
576
|
+
if args.show_config:
|
|
577
|
+
format_show_config(
|
|
578
|
+
provider_name,
|
|
579
|
+
model,
|
|
580
|
+
max_context,
|
|
581
|
+
ollama_host,
|
|
582
|
+
timeout,
|
|
583
|
+
profile=None if profile is None else profile.name,
|
|
584
|
+
config_path=config_path,
|
|
585
|
+
)
|
|
586
|
+
return 0
|
|
587
|
+
names = ", ".join(KNOWN)
|
|
588
|
+
if provider_name is None:
|
|
589
|
+
print(f"Error: provider is required ({names})", file=sys.stderr)
|
|
590
|
+
return 2
|
|
591
|
+
if provider_name not in KNOWN:
|
|
592
|
+
print(f"Error: unknown provider '{provider_name}' ({names})", file=sys.stderr)
|
|
593
|
+
return 2
|
|
594
|
+
if args.list_models:
|
|
595
|
+
if timeout is None or _reject_gemini_timeout(provider_name, timeout):
|
|
596
|
+
return 2
|
|
597
|
+
return run_list_models(
|
|
598
|
+
provider_name,
|
|
599
|
+
ollama_host,
|
|
600
|
+
timeout=timeout,
|
|
601
|
+
)
|
|
602
|
+
if model is None:
|
|
603
|
+
print("Error: model is required", file=sys.stderr)
|
|
604
|
+
return 2
|
|
605
|
+
if timeout is None or _reject_gemini_timeout(provider_name, timeout):
|
|
606
|
+
return 2
|
|
607
|
+
if args.question is None:
|
|
608
|
+
return run_interactive(
|
|
609
|
+
provider_name,
|
|
610
|
+
model,
|
|
611
|
+
ollama_host,
|
|
612
|
+
max_context,
|
|
613
|
+
stream=stream,
|
|
614
|
+
timeout=timeout,
|
|
615
|
+
)
|
|
616
|
+
return run_oneshot(
|
|
617
|
+
args.question,
|
|
618
|
+
provider_name,
|
|
619
|
+
model,
|
|
620
|
+
ollama_host,
|
|
621
|
+
max_context,
|
|
622
|
+
stream=stream,
|
|
623
|
+
timeout=timeout,
|
|
624
|
+
)
|