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.
@@ -0,0 +1,108 @@
1
+ """Ollama provider. Not part of the public package API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Generator, Iterator
6
+ from contextlib import contextmanager
7
+
8
+ import httpx
9
+ from ollama import Client, ResponseError
10
+
11
+ from .catalog import CATALOG
12
+ from .errors import ChatError, one_line
13
+
14
+
15
+ class OllamaProvider:
16
+ """Chat through the official Ollama client."""
17
+
18
+ mode = CATALOG["ollama"].mode
19
+ supports_stream = True
20
+
21
+ def __init__(self, host: str, timeout: float) -> None:
22
+ self.host = host.rstrip("/")
23
+ self.timeout = timeout
24
+
25
+ def chat(
26
+ self,
27
+ messages: list[dict[str, str]],
28
+ model: str,
29
+ system_prompt: str,
30
+ ) -> str:
31
+ payload = _messages(messages, system_prompt)
32
+ with _session(self, model) as client:
33
+ try:
34
+ response = client.chat(model=model, messages=payload, stream=False)
35
+ content = response.message.content
36
+ except AttributeError as exc:
37
+ raise ChatError("the provider returned an invalid response") from exc
38
+ if content is None or not str(content).strip():
39
+ raise ChatError("the provider returned an invalid response")
40
+ return str(content)
41
+
42
+ def stream(
43
+ self,
44
+ messages: list[dict[str, str]],
45
+ model: str,
46
+ system_prompt: str,
47
+ ) -> Iterator[str]:
48
+ payload = _messages(messages, system_prompt)
49
+ with _session(self, model) as client:
50
+ for chunk in client.chat(model=model, messages=payload, stream=True):
51
+ try:
52
+ content = chunk.message.content
53
+ except AttributeError as exc:
54
+ raise ChatError("the provider returned an invalid response") from exc
55
+ if content:
56
+ yield str(content)
57
+
58
+ def list_models(self) -> list[str]:
59
+ with _session(self) as client:
60
+ try:
61
+ listed = client.list()
62
+ names = [item.model for item in listed.models]
63
+ except AttributeError as exc:
64
+ raise ChatError("the provider returned an invalid response") from exc
65
+ if any(name is None or not str(name).strip() for name in names):
66
+ raise ChatError("the provider returned an invalid response")
67
+ return [str(name) for name in names]
68
+
69
+
70
+ def _timeout(seconds: float) -> httpx.Timeout:
71
+ return httpx.Timeout(
72
+ connect=min(5.0, seconds),
73
+ read=seconds,
74
+ write=min(30.0, seconds),
75
+ pool=min(5.0, seconds),
76
+ )
77
+
78
+
79
+ def _messages(
80
+ messages: list[dict[str, str]],
81
+ system_prompt: str,
82
+ ) -> list[dict[str, str]]:
83
+ return [{"role": "system", "content": system_prompt}, *list(messages)]
84
+
85
+
86
+ def _missing_model(model: str) -> ChatError:
87
+ return ChatError(f"Ollama model '{model}' is not installed.\nollama pull {model}")
88
+
89
+
90
+ @contextmanager
91
+ def _session(provider: OllamaProvider, model: str | None = None) -> Generator[Client, None, None]:
92
+ client = Client(host=provider.host, timeout=_timeout(provider.timeout))
93
+ try:
94
+ yield client
95
+ except ChatError:
96
+ raise
97
+ except httpx.TimeoutException:
98
+ raise ChatError("Ollama request timed out") from None
99
+ except ConnectionError:
100
+ raise ChatError(f"unable to connect to Ollama at {provider.host}") from None
101
+ except ResponseError as exc:
102
+ if model is not None and exc.status_code == 404:
103
+ raise _missing_model(model) from None
104
+ raise ChatError(one_line(exc)) from None
105
+ except Exception as exc:
106
+ raise ChatError(one_line(exc)) from None
107
+ finally:
108
+ client.close()
@@ -0,0 +1,129 @@
1
+ """OpenAI Responses provider. Not part of the public package API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Iterator
7
+ from typing import cast
8
+
9
+ from openai import (
10
+ APIConnectionError,
11
+ APIStatusError,
12
+ APITimeoutError,
13
+ AuthenticationError,
14
+ BadRequestError,
15
+ InternalServerError,
16
+ NotFoundError,
17
+ OpenAI,
18
+ OpenAIError,
19
+ PermissionDeniedError,
20
+ RateLimitError,
21
+ )
22
+ from openai.types.responses import ResponseInputParam
23
+
24
+ from .catalog import CATALOG
25
+ from .errors import (
26
+ ChatError,
27
+ looks_like_context_limit,
28
+ one_line,
29
+ )
30
+
31
+
32
+ class OpenAIProvider:
33
+ """Chat through the OpenAI Responses API."""
34
+
35
+ mode = CATALOG["openai"].mode
36
+ supports_stream = True
37
+
38
+ def __init__(self, timeout: float) -> None:
39
+ self.timeout = timeout
40
+
41
+ def chat(
42
+ self,
43
+ messages: list[dict[str, str]],
44
+ model: str,
45
+ system_prompt: str,
46
+ ) -> str:
47
+ client = _client(self.timeout)
48
+ try:
49
+ response = client.responses.create(
50
+ model=model,
51
+ instructions=system_prompt,
52
+ input=cast(ResponseInputParam, list(messages)),
53
+ timeout=self.timeout,
54
+ )
55
+ except ChatError:
56
+ raise
57
+ except OpenAIError as exc:
58
+ raise _translate(exc, model) from None
59
+ except Exception as exc:
60
+ raise ChatError(one_line(exc)) from None
61
+ text = (response.output_text or "").strip()
62
+ if not text:
63
+ raise ChatError("the provider returned an invalid response")
64
+ return response.output_text
65
+
66
+ def stream(
67
+ self,
68
+ messages: list[dict[str, str]],
69
+ model: str,
70
+ system_prompt: str,
71
+ ) -> Iterator[str]:
72
+ client = _client(self.timeout)
73
+ try:
74
+ with client.responses.stream(
75
+ model=model,
76
+ instructions=system_prompt,
77
+ input=cast(ResponseInputParam, list(messages)),
78
+ timeout=self.timeout,
79
+ ) as stream:
80
+ for event in stream:
81
+ if getattr(event, "type", "") != "response.output_text.delta":
82
+ continue
83
+ delta = getattr(event, "delta", "") or ""
84
+ if delta:
85
+ yield delta
86
+ except ChatError:
87
+ raise
88
+ except OpenAIError as exc:
89
+ raise _translate(exc, model) from None
90
+ except Exception as exc:
91
+ raise ChatError(one_line(exc)) from None
92
+
93
+ def list_models(self) -> list[str]:
94
+ client = _client(self.timeout)
95
+ try:
96
+ return [item.id for item in client.models.list(timeout=self.timeout)]
97
+ except ChatError:
98
+ raise
99
+ except OpenAIError as exc:
100
+ raise _translate(exc, "") from None
101
+ except Exception as exc:
102
+ raise ChatError(one_line(exc)) from None
103
+
104
+
105
+ def _client(timeout: float) -> OpenAI:
106
+ key = os.environ.get("OPENAI_API_KEY", "").strip()
107
+ if not key:
108
+ raise ChatError("OPENAI_API_KEY is not configured")
109
+ return OpenAI(api_key=key, timeout=timeout)
110
+
111
+
112
+ def _translate(exc: OpenAIError, model: str) -> ChatError:
113
+ if isinstance(exc, (AuthenticationError, PermissionDeniedError)):
114
+ return ChatError("OpenAI authentication failed")
115
+ if isinstance(exc, RateLimitError):
116
+ return ChatError("OpenAI rate limit reached")
117
+ if isinstance(exc, APITimeoutError):
118
+ return ChatError("OpenAI request timed out")
119
+ if isinstance(exc, APIConnectionError):
120
+ return ChatError("network error talking to OpenAI")
121
+ if isinstance(exc, NotFoundError):
122
+ return ChatError(f"model '{model}' is not available")
123
+ if isinstance(exc, InternalServerError):
124
+ return ChatError("OpenAI is unavailable")
125
+ if isinstance(exc, BadRequestError) and looks_like_context_limit(str(exc)):
126
+ return ChatError("the conversation is too long for this model")
127
+ if isinstance(exc, APIStatusError) and exc.status_code >= 500:
128
+ return ChatError("OpenAI is unavailable")
129
+ return ChatError(one_line(exc))
@@ -0,0 +1,10 @@
1
+ """Version information for the ``lupaxa.basic_cli_chatbot`` package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+
7
+
8
+ def get_version() -> str:
9
+ """Return the current package version string."""
10
+ return __version__
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.5
2
+ Name: lupaxa-basic-cli-chatbot
3
+ Version: 0.1.0
4
+ Summary: A simple command-line AI chatbot with conversation context.
5
+ Project-URL: Homepage, https://github.com/lupaxa-ai-toolbox/basic-cli-chatbot
6
+ Project-URL: Documentation, https://github.com/lupaxa-ai-toolbox/basic-cli-chatbot
7
+ Project-URL: Repository, https://github.com/lupaxa-ai-toolbox/basic-cli-chatbot
8
+ Project-URL: Issues, https://github.com/lupaxa-ai-toolbox/basic-cli-chatbot/issues
9
+ Author: The Lupaxa Project
10
+ License: MIT License
11
+
12
+ Copyright (c) The Lupaxa Project
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENCE
32
+ Keywords: chatbot,cli,openai
33
+ Classifier: Environment :: Console
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Operating System :: OS Independent
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Programming Language :: Python :: 3.14
43
+ Classifier: Topic :: Utilities
44
+ Requires-Python: >=3.10
45
+ Requires-Dist: google-genai
46
+ Requires-Dist: httpx
47
+ Requires-Dist: ollama
48
+ Requires-Dist: openai>=2
49
+ Requires-Dist: pyyaml
50
+ Requires-Dist: xai-sdk
51
+ Provides-Extra: dev
52
+ Requires-Dist: bump-my-version>=1.2.0; extra == 'dev'
53
+ Requires-Dist: hatch>=1.12.0; extra == 'dev'
54
+ Requires-Dist: mypy>=1.12.0; extra == 'dev'
55
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
56
+ Requires-Dist: pytest>=8.0; extra == 'dev'
57
+ Requires-Dist: ruff>=0.6.0; extra == 'dev'
58
+ Provides-Extra: test
59
+ Requires-Dist: pytest-cov>=5.0; extra == 'test'
60
+ Requires-Dist: pytest>=8.0; extra == 'test'
61
+ Description-Content-Type: text/markdown
62
+
63
+ <p align="center">
64
+ <a href="https://github.com/lupaxa-ai-toolbox">
65
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/organisations/ai-toolbox/readme-logo.png" alt="AI Toolbox" />
66
+ </a>
67
+ </p>
68
+
69
+ <h1 align="center">Basic CLI Chatbot</h1>
70
+
71
+ A command-line chatbot that talks to OpenAI, Gemini, Grok, or a local Ollama
72
+ server. A chat requires a provider and a model.
73
+
74
+ The PyPI name is `lupaxa-basic-cli-chatbot`. The console script is
75
+ `basic-cli-chatbot`.
76
+
77
+ ## Install
78
+
79
+ Python 3.10 or newer. Set `OPENAI_API_KEY` for `--provider openai`,
80
+ `GEMINI_API_KEY` for `--provider gemini`, and `XAI_API_KEY` for
81
+ `--provider grok`. Ollama uses a local server and does not need those keys.
82
+
83
+ ```bash
84
+ pip install lupaxa-basic-cli-chatbot
85
+ ```
86
+
87
+ ## Homebrew
88
+
89
+ ```bash
90
+ brew tap the-lupaxa-project/tap
91
+ brew trust the-lupaxa-project/tap
92
+ brew install basic-cli-chatbot
93
+ ```
94
+
95
+ ## Usage
96
+
97
+ A command with no question opens a prompt. A question after the flags asks
98
+ once and exits.
99
+
100
+ ```bash
101
+ basic-cli-chatbot --provider openai --model gpt-5.6-luna
102
+ basic-cli-chatbot --provider openai --model gpt-5.6-luna "What is 2+2?"
103
+ basic-cli-chatbot --provider ollama --model llama3.2
104
+ basic-cli-chatbot --provider grok --model grok-4.6
105
+ basic-cli-chatbot --list-models --provider ollama
106
+ basic-cli-chatbot --show-config --provider gemini
107
+ basic-cli-chatbot --version
108
+ basic-cli-chatbot --help
109
+ ```
110
+
111
+ `--provider` overrides `BASIC_CLI_CHATBOT_PROVIDER`. `--model` overrides
112
+ `BASIC_CLI_CHATBOT_MODEL`.
113
+
114
+ Ollama talks to a server at `http://localhost:11434`. That server has to be
115
+ running, and the model has to be installed already (`ollama pull llama3.2`).
116
+
117
+ A YAML profile file can supply the provider, the model, and the optional
118
+ chat settings. The default path is `$XDG_CONFIG_HOME/basic-cli-chatbot/config.yaml`,
119
+ or `~/.config/basic-cli-chatbot/config.yaml` when `XDG_CONFIG_HOME` is unset.
120
+ `--config` points at another file.
121
+
122
+ ```yaml
123
+ default:
124
+ provider: openai
125
+ model: gpt-5.6-luna
126
+ code-review:
127
+ provider: ollama
128
+ model: llama3.2
129
+ ollama-host: http://127.0.0.1:11434
130
+ timeout: 120
131
+ ```
132
+
133
+ `--profile code-review` uses that profile and cannot be combined with
134
+ `--provider` or `--model`. With neither of those flags and no `--profile`,
135
+ a `default` profile is used. `--ollama-host`, `--max-context-messages`,
136
+ `--timeout`, `--stream`, and `--no-stream` replace the profile value when
137
+ you pass them. `--validate` checks the file and exits. API keys stay in
138
+ the environment.
139
+
140
+ `--ollama-host` overrides `http://localhost:11434`.
141
+
142
+ `--max-context-messages` defaults to `0`, which keeps the whole
143
+ conversation.
144
+
145
+ Replies print as they arrive. `--no-stream` prints the reply in one piece.
146
+
147
+ The reply wait is 60 seconds for OpenAI, Gemini, and Grok, and 300 seconds
148
+ for Ollama. `--timeout` overrides that. `BASIC_CLI_CHATBOT_TIMEOUT` is used
149
+ only when `--timeout` is unset and the profile has no `timeout`.
150
+
151
+ `exit` and `quit` stop the prompt. `clear` drops the conversation.
152
+ `/context` prints how many messages are kept. `/provider` and `/model`
153
+ print the current names.
154
+
155
+ `--show-config` reports a key as `configured` or `not configured` and
156
+ does not print the secret.
157
+
158
+ ## Development
159
+
160
+ ```bash
161
+ make init
162
+ make python-install-dev
163
+ make python-check
164
+ ```
165
+
166
+ <a href="https://github.com/the-lupaxa-project">
167
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/components/footer-for-child-orgs.svg" alt="The Lupaxa Project Footer" width="100%" />
168
+ </a>
@@ -0,0 +1,19 @@
1
+ lupaxa/basic_cli_chatbot/__init__.py,sha256=MXPTfLU3IeI3xx6rZeL5nG88Lxz2_FHa31hSsjkzvw4,206
2
+ lupaxa/basic_cli_chatbot/__main__.py,sha256=IpC3HddMjUotCB8D8LmLDqVjOJsLmXy2FtYWjUKgjw0,183
3
+ lupaxa/basic_cli_chatbot/chat.py,sha256=cq2qncvCYg3qx3mkIr1YdeU6l7UpI8LfW0Br6XLy9bw,2210
4
+ lupaxa/basic_cli_chatbot/cli.py,sha256=ivkaxgi-j4n4W7y_1F-NRsKCD3drW9N7d7JDPf9FXjs,18837
5
+ lupaxa/basic_cli_chatbot/config.py,sha256=sdpTXoY6crseKhLJ1fUfK9HFj4BixodwmbjUT75vJS0,7229
6
+ lupaxa/basic_cli_chatbot/version.py,sha256=IpDdrHIpa5MfcRZNvXXb9rjD2SOIucXfMPp2Ahcic10,235
7
+ lupaxa/basic_cli_chatbot/providers/__init__.py,sha256=4TJgNLdYmB7taTEMx8E5tPgVc3K1qHmVNblyMoe4-zM,958
8
+ lupaxa/basic_cli_chatbot/providers/base.py,sha256=oBkRV7QoumuFWhpq2u7tO3igCMdVXyqWfRHqHmzMbyw,847
9
+ lupaxa/basic_cli_chatbot/providers/catalog.py,sha256=CkG8wlJ_PUpmcD1ip6W5-3byAq3w_iRFXSYW59aZDCc,1105
10
+ lupaxa/basic_cli_chatbot/providers/errors.py,sha256=bUUNJSk2thMpykH0ijRk92KkkC38CCHgkHAhV88OQEE,706
11
+ lupaxa/basic_cli_chatbot/providers/gemini.py,sha256=lZSEk67XSldVugFYe9Wdc3iWzEPzBq82BtoB1C699Ww,4136
12
+ lupaxa/basic_cli_chatbot/providers/grok.py,sha256=riTl8bW0oiCMYQfgidXyKlW71qD9t5Rcuf-jQdx6-I0,4702
13
+ lupaxa/basic_cli_chatbot/providers/ollama.py,sha256=bnoCYFl5_czxIjHC81K5bBF_Z92nG5UC7eHN4i-JMWw,3670
14
+ lupaxa/basic_cli_chatbot/providers/openai.py,sha256=lOG1JkpWu0iBz4U9pw4ZzA3YgBmzEL7l6V64zR94yQ4,4155
15
+ lupaxa_basic_cli_chatbot-0.1.0.dist-info/METADATA,sha256=cT1SST7OUJqaSMpyyHPleGTV5VzBQyje1KElxI9Zyjg,6369
16
+ lupaxa_basic_cli_chatbot-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
17
+ lupaxa_basic_cli_chatbot-0.1.0.dist-info/entry_points.txt,sha256=bhAPBzeY1DWcmw3NQvL2hHe85d9OvtUi4oR2RyRfbuk,72
18
+ lupaxa_basic_cli_chatbot-0.1.0.dist-info/licenses/LICENCE,sha256=RXShyrlT7e281QX54JLm3YrhOlC-TJxObadJl1gH5Es,1070
19
+ lupaxa_basic_cli_chatbot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ basic-cli-chatbot = lupaxa.basic_cli_chatbot.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) The Lupaxa Project
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. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.