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,210 @@
|
|
|
1
|
+
"""YAML profile file. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from .providers import KNOWN
|
|
13
|
+
|
|
14
|
+
_ALLOWED = frozenset(
|
|
15
|
+
{"provider", "model", "ollama-host", "max-context-messages", "stream", "timeout"}
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigError(Exception):
|
|
20
|
+
"""Config failure. The message is the text after ``Error: ``."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Profile:
|
|
25
|
+
"""One named chat setup. Optional fields stay unset when the file omits them."""
|
|
26
|
+
|
|
27
|
+
name: str
|
|
28
|
+
provider: str
|
|
29
|
+
model: str
|
|
30
|
+
ollama_host: str | None = None
|
|
31
|
+
max_context_messages: int | None = None
|
|
32
|
+
stream: bool | None = None
|
|
33
|
+
timeout: float | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ConfigFile:
|
|
38
|
+
"""Profiles in file order."""
|
|
39
|
+
|
|
40
|
+
path: Path
|
|
41
|
+
profiles: tuple[Profile, ...]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _Loader(yaml.SafeLoader):
|
|
45
|
+
"""Safe loader that rejects a repeated string key."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _construct_mapping(
|
|
49
|
+
loader: yaml.SafeLoader,
|
|
50
|
+
node: yaml.MappingNode,
|
|
51
|
+
deep: bool = False,
|
|
52
|
+
) -> dict[object, object]:
|
|
53
|
+
mapping: dict[object, object] = {}
|
|
54
|
+
seen: set[str] = set()
|
|
55
|
+
for key_node, value_node in node.value:
|
|
56
|
+
key = loader.construct_object(key_node, deep=deep)
|
|
57
|
+
try:
|
|
58
|
+
hash(key)
|
|
59
|
+
except TypeError:
|
|
60
|
+
raise ConfigError("profile names must be strings") from None
|
|
61
|
+
if isinstance(key, str):
|
|
62
|
+
folded = key.strip().casefold()
|
|
63
|
+
if folded in seen:
|
|
64
|
+
raise ConfigError(f"duplicate profile '{folded}'")
|
|
65
|
+
seen.add(folded)
|
|
66
|
+
mapping[key] = loader.construct_object(value_node, deep=deep)
|
|
67
|
+
return mapping
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_Loader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def default_config_path() -> Path:
|
|
74
|
+
"""Return the user config path. ``XDG_CONFIG_HOME`` wins when it is non-empty."""
|
|
75
|
+
raw = os.environ.get("XDG_CONFIG_HOME")
|
|
76
|
+
base = Path(raw.strip()) if raw is not None and raw.strip() else Path.home() / ".config"
|
|
77
|
+
return base / "basic-cli-chatbot" / "config.yaml"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def load_config(path: Path) -> ConfigFile:
|
|
81
|
+
"""Read one YAML document. Raise ``ConfigError`` on the first problem."""
|
|
82
|
+
try:
|
|
83
|
+
text = path.read_text(encoding="utf-8")
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
raise ConfigError(f"config file not found: {path}") from None
|
|
86
|
+
except OSError:
|
|
87
|
+
raise ConfigError(f"unable to read config file: {path}") from None
|
|
88
|
+
try:
|
|
89
|
+
documents = list(yaml.load_all(text, Loader=_Loader))
|
|
90
|
+
except ConfigError:
|
|
91
|
+
raise
|
|
92
|
+
except yaml.YAMLError as exc:
|
|
93
|
+
cause = exc.__cause__
|
|
94
|
+
if isinstance(cause, ConfigError):
|
|
95
|
+
raise cause from None
|
|
96
|
+
detail = str(exc).splitlines()
|
|
97
|
+
first = detail[0] if detail and detail[0].strip() else "invalid YAML"
|
|
98
|
+
raise ConfigError(f"invalid config file: {first}") from None
|
|
99
|
+
if len(documents) > 1:
|
|
100
|
+
raise ConfigError("config file must be a single document")
|
|
101
|
+
root: object = documents[0] if documents else None
|
|
102
|
+
return ConfigFile(path=path, profiles=_profiles(root))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def find_profile(config: ConfigFile, name: str) -> Profile:
|
|
106
|
+
"""Return the profile whose stripped name matches, ignoring case."""
|
|
107
|
+
key = name.strip().casefold()
|
|
108
|
+
if not key:
|
|
109
|
+
raise ConfigError("profile is required")
|
|
110
|
+
for profile in config.profiles:
|
|
111
|
+
if profile.name.casefold() == key:
|
|
112
|
+
return profile
|
|
113
|
+
known = ", ".join(profile.name for profile in config.profiles)
|
|
114
|
+
raise ConfigError(f"unknown profile '{key}' ({known})")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _profiles(root: object) -> tuple[Profile, ...]:
|
|
118
|
+
if root is None:
|
|
119
|
+
root = {}
|
|
120
|
+
if not isinstance(root, dict):
|
|
121
|
+
raise ConfigError("config file must be a mapping")
|
|
122
|
+
profiles: list[Profile] = []
|
|
123
|
+
for raw_name, raw_body in root.items():
|
|
124
|
+
if not isinstance(raw_name, str):
|
|
125
|
+
raise ConfigError("profile names must be strings")
|
|
126
|
+
name = raw_name.strip()
|
|
127
|
+
if not name:
|
|
128
|
+
raise ConfigError("profile name is empty")
|
|
129
|
+
if not isinstance(raw_body, dict):
|
|
130
|
+
raise ConfigError(f"profile '{name}' must be a mapping")
|
|
131
|
+
profiles.append(_profile(name, raw_body))
|
|
132
|
+
return tuple(profiles)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _profile(name: str, body: dict[object, object]) -> Profile:
|
|
136
|
+
for key in body:
|
|
137
|
+
if not isinstance(key, str) or key not in _ALLOWED:
|
|
138
|
+
shown = key if isinstance(key, str) else str(key)
|
|
139
|
+
raise ConfigError(f"profile '{name}' has unknown key '{shown}'")
|
|
140
|
+
provider = _required_text(name, body, "provider")
|
|
141
|
+
if provider.strip().casefold() not in KNOWN:
|
|
142
|
+
joined = ", ".join(KNOWN)
|
|
143
|
+
shown = provider.strip().casefold()
|
|
144
|
+
raise ConfigError(f"profile '{name}' has unknown provider '{shown}' ({joined})")
|
|
145
|
+
model = _required_text(name, body, "model")
|
|
146
|
+
return Profile(
|
|
147
|
+
name=name,
|
|
148
|
+
provider=provider.strip().casefold(),
|
|
149
|
+
model=model.strip(),
|
|
150
|
+
ollama_host=_optional_host(name, body),
|
|
151
|
+
max_context_messages=_optional_limit(name, body),
|
|
152
|
+
stream=_optional_stream(name, body),
|
|
153
|
+
timeout=_optional_timeout(name, body),
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _required_text(name: str, body: dict[object, object], key: str) -> str:
|
|
158
|
+
if key not in body or body[key] is None:
|
|
159
|
+
raise ConfigError(f"profile '{name}' is missing {key}")
|
|
160
|
+
value = body[key]
|
|
161
|
+
if not isinstance(value, str):
|
|
162
|
+
raise ConfigError(f"profile '{name}' {key} must be a string")
|
|
163
|
+
if not value.strip():
|
|
164
|
+
raise ConfigError(f"profile '{name}' is missing {key}")
|
|
165
|
+
return value
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _optional_host(name: str, body: dict[object, object]) -> str | None:
|
|
169
|
+
if "ollama-host" not in body:
|
|
170
|
+
return None
|
|
171
|
+
value = body["ollama-host"]
|
|
172
|
+
if not isinstance(value, str) or not value.strip():
|
|
173
|
+
raise ConfigError(f"profile '{name}' ollama-host must be a non-empty string")
|
|
174
|
+
return value.strip()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _optional_limit(name: str, body: dict[object, object]) -> int | None:
|
|
178
|
+
if "max-context-messages" not in body:
|
|
179
|
+
return None
|
|
180
|
+
value = body["max-context-messages"]
|
|
181
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
182
|
+
raise ConfigError(f"profile '{name}' max-context-messages must be an integer")
|
|
183
|
+
if value < 0:
|
|
184
|
+
raise ConfigError(f"profile '{name}' max-context-messages must be 0 or greater")
|
|
185
|
+
return value
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _optional_stream(name: str, body: dict[object, object]) -> bool | None:
|
|
189
|
+
if "stream" not in body:
|
|
190
|
+
return None
|
|
191
|
+
value = body["stream"]
|
|
192
|
+
if not isinstance(value, bool):
|
|
193
|
+
raise ConfigError(f"profile '{name}' stream must be true or false")
|
|
194
|
+
return value
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _optional_timeout(name: str, body: dict[object, object]) -> float | None:
|
|
198
|
+
if "timeout" not in body:
|
|
199
|
+
return None
|
|
200
|
+
value = body["timeout"]
|
|
201
|
+
message = f"profile '{name}' timeout must be a number of seconds greater than 0"
|
|
202
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
203
|
+
raise ConfigError(message)
|
|
204
|
+
try:
|
|
205
|
+
number = float(value)
|
|
206
|
+
except OverflowError:
|
|
207
|
+
raise ConfigError(message) from None
|
|
208
|
+
if not math.isfinite(number) or number <= 0:
|
|
209
|
+
raise ConfigError(message)
|
|
210
|
+
return number
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Provider registry. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .base import Provider
|
|
6
|
+
from .errors import ChatError
|
|
7
|
+
|
|
8
|
+
KNOWN = ("openai", "gemini", "grok", "ollama")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def build(name: str, *, ollama_host: str, timeout: float) -> Provider:
|
|
12
|
+
"""Return the provider for a CLI name. This is the only name-to-class map."""
|
|
13
|
+
key = name.strip().casefold()
|
|
14
|
+
if key == "openai":
|
|
15
|
+
from .openai import OpenAIProvider
|
|
16
|
+
|
|
17
|
+
return OpenAIProvider(timeout)
|
|
18
|
+
if key == "gemini":
|
|
19
|
+
from .gemini import GeminiProvider
|
|
20
|
+
|
|
21
|
+
return GeminiProvider(timeout)
|
|
22
|
+
if key == "grok":
|
|
23
|
+
from .grok import GrokProvider
|
|
24
|
+
|
|
25
|
+
return GrokProvider(timeout)
|
|
26
|
+
if key == "ollama":
|
|
27
|
+
from .ollama import OllamaProvider
|
|
28
|
+
|
|
29
|
+
return OllamaProvider(ollama_host, timeout)
|
|
30
|
+
joined = ", ".join(KNOWN)
|
|
31
|
+
raise ChatError(f"unknown provider '{key}' ({joined})")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
__all__ = ["KNOWN", "Provider", "build"]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Provider interface. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Provider(Protocol):
|
|
10
|
+
"""One chat backend selected for the process."""
|
|
11
|
+
|
|
12
|
+
mode: str
|
|
13
|
+
supports_stream: bool
|
|
14
|
+
|
|
15
|
+
def chat(
|
|
16
|
+
self,
|
|
17
|
+
messages: list[dict[str, str]],
|
|
18
|
+
model: str,
|
|
19
|
+
system_prompt: str,
|
|
20
|
+
) -> str:
|
|
21
|
+
"""Return the full assistant reply."""
|
|
22
|
+
raise NotImplementedError
|
|
23
|
+
|
|
24
|
+
def stream(
|
|
25
|
+
self,
|
|
26
|
+
messages: list[dict[str, str]],
|
|
27
|
+
model: str,
|
|
28
|
+
system_prompt: str,
|
|
29
|
+
) -> Iterator[str]:
|
|
30
|
+
"""Yield reply text deltas."""
|
|
31
|
+
raise NotImplementedError
|
|
32
|
+
|
|
33
|
+
def list_models(self) -> list[str]:
|
|
34
|
+
"""Return model names accepted by ``--model``."""
|
|
35
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Provider facts that do not load an SDK. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import NamedTuple
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ProviderFacts(NamedTuple):
|
|
9
|
+
"""Mode, optional API-key variable, and built-in reply timeout in seconds."""
|
|
10
|
+
|
|
11
|
+
mode: str
|
|
12
|
+
api_key_env: str | None
|
|
13
|
+
timeout_seconds: float
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
CATALOG: dict[str, ProviderFacts] = {
|
|
17
|
+
"openai": ProviderFacts(
|
|
18
|
+
mode="Remote",
|
|
19
|
+
api_key_env="OPENAI_API_KEY",
|
|
20
|
+
timeout_seconds=60,
|
|
21
|
+
),
|
|
22
|
+
"gemini": ProviderFacts(
|
|
23
|
+
mode="Remote",
|
|
24
|
+
api_key_env="GEMINI_API_KEY",
|
|
25
|
+
timeout_seconds=60,
|
|
26
|
+
),
|
|
27
|
+
"grok": ProviderFacts(
|
|
28
|
+
mode="Remote",
|
|
29
|
+
api_key_env="XAI_API_KEY",
|
|
30
|
+
timeout_seconds=60,
|
|
31
|
+
),
|
|
32
|
+
"ollama": ProviderFacts(mode="Local", api_key_env=None, timeout_seconds=300),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def gemini_timeout_ms(seconds: float) -> int:
|
|
37
|
+
"""Convert seconds to Gemini's millisecond timeout."""
|
|
38
|
+
milliseconds = round(seconds * 1000)
|
|
39
|
+
if milliseconds < 1:
|
|
40
|
+
raise ValueError("timeout must be at least 1 millisecond for Gemini")
|
|
41
|
+
return milliseconds
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""User-facing chat failures. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ChatError(Exception):
|
|
7
|
+
"""Failure whose message is printed after ``Error: ``."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def one_line(exc: BaseException) -> str:
|
|
11
|
+
"""Return the first line of an exception, capped at 200 characters."""
|
|
12
|
+
raw = str(exc).strip()
|
|
13
|
+
if not raw:
|
|
14
|
+
return "the provider returned an invalid response"
|
|
15
|
+
return raw.splitlines()[0][:200]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def looks_like_context_limit(text: str) -> bool:
|
|
19
|
+
"""Return whether a provider message is a context-window rejection."""
|
|
20
|
+
lowered = text.lower()
|
|
21
|
+
return "context" in lowered and any(word in lowered for word in ("length", "window", "token"))
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Gemini 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
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from google import genai
|
|
10
|
+
from google.genai import errors, types
|
|
11
|
+
|
|
12
|
+
from .catalog import CATALOG, gemini_timeout_ms
|
|
13
|
+
from .errors import (
|
|
14
|
+
ChatError,
|
|
15
|
+
looks_like_context_limit,
|
|
16
|
+
one_line,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GeminiProvider:
|
|
21
|
+
"""Chat through the Google GenAI SDK."""
|
|
22
|
+
|
|
23
|
+
mode = CATALOG["gemini"].mode
|
|
24
|
+
supports_stream = True
|
|
25
|
+
|
|
26
|
+
def __init__(self, timeout: float) -> None:
|
|
27
|
+
self.timeout = timeout
|
|
28
|
+
|
|
29
|
+
def chat(
|
|
30
|
+
self,
|
|
31
|
+
messages: list[dict[str, str]],
|
|
32
|
+
model: str,
|
|
33
|
+
system_prompt: str,
|
|
34
|
+
) -> str:
|
|
35
|
+
client = _client(self.timeout)
|
|
36
|
+
try:
|
|
37
|
+
response = client.models.generate_content(
|
|
38
|
+
model=model,
|
|
39
|
+
contents=_contents(messages),
|
|
40
|
+
config=_config(system_prompt),
|
|
41
|
+
)
|
|
42
|
+
except Exception as exc:
|
|
43
|
+
raise _guard(exc, model) from None
|
|
44
|
+
raw = response.text
|
|
45
|
+
if raw is None or not raw.strip():
|
|
46
|
+
raise ChatError("the provider returned an invalid response")
|
|
47
|
+
return raw
|
|
48
|
+
|
|
49
|
+
def stream(
|
|
50
|
+
self,
|
|
51
|
+
messages: list[dict[str, str]],
|
|
52
|
+
model: str,
|
|
53
|
+
system_prompt: str,
|
|
54
|
+
) -> Iterator[str]:
|
|
55
|
+
client = _client(self.timeout)
|
|
56
|
+
try:
|
|
57
|
+
chunks = client.models.generate_content_stream(
|
|
58
|
+
model=model,
|
|
59
|
+
contents=_contents(messages),
|
|
60
|
+
config=_config(system_prompt),
|
|
61
|
+
)
|
|
62
|
+
for chunk in chunks:
|
|
63
|
+
text = chunk.text or ""
|
|
64
|
+
if text:
|
|
65
|
+
yield text
|
|
66
|
+
except Exception as exc:
|
|
67
|
+
raise _guard(exc, model) from None
|
|
68
|
+
|
|
69
|
+
def list_models(self) -> list[str]:
|
|
70
|
+
client = _client(self.timeout)
|
|
71
|
+
try:
|
|
72
|
+
names: list[str] = []
|
|
73
|
+
for item in client.models.list():
|
|
74
|
+
name = item.name or ""
|
|
75
|
+
if name.startswith("models/"):
|
|
76
|
+
name = name[len("models/") :]
|
|
77
|
+
if name:
|
|
78
|
+
names.append(name)
|
|
79
|
+
return names
|
|
80
|
+
except Exception as exc:
|
|
81
|
+
raise _guard(exc, "") from None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _client(timeout: float) -> genai.Client:
|
|
85
|
+
key = os.environ.get("GEMINI_API_KEY", "").strip()
|
|
86
|
+
if not key:
|
|
87
|
+
raise ChatError("GEMINI_API_KEY is not configured")
|
|
88
|
+
return genai.Client(
|
|
89
|
+
api_key=key,
|
|
90
|
+
http_options=types.HttpOptions(timeout=gemini_timeout_ms(timeout)),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _config(system_prompt: str) -> types.GenerateContentConfig:
|
|
95
|
+
return types.GenerateContentConfig(system_instruction=system_prompt)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _contents(messages: list[dict[str, str]]) -> list[dict[str, object]]:
|
|
99
|
+
contents: list[dict[str, object]] = []
|
|
100
|
+
for message in messages:
|
|
101
|
+
role = "model" if message["role"] == "assistant" else "user"
|
|
102
|
+
contents.append({"role": role, "parts": [{"text": message["content"]}]})
|
|
103
|
+
return contents
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _guard(exc: Exception, model: str) -> ChatError:
|
|
107
|
+
if isinstance(exc, errors.APIError):
|
|
108
|
+
return _translate(exc, model)
|
|
109
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
110
|
+
return ChatError("Gemini request timed out")
|
|
111
|
+
if isinstance(exc, httpx.TransportError):
|
|
112
|
+
return ChatError("network error talking to Gemini")
|
|
113
|
+
return ChatError(one_line(exc))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _translate(exc: errors.APIError, model: str) -> ChatError:
|
|
117
|
+
code = exc.code
|
|
118
|
+
detail = exc.message or str(exc)
|
|
119
|
+
if code in {401, 403}:
|
|
120
|
+
return ChatError("Gemini authentication failed")
|
|
121
|
+
if code == 429:
|
|
122
|
+
return ChatError("Gemini rate limit reached")
|
|
123
|
+
if code == 404:
|
|
124
|
+
return ChatError(f"model '{model}' is not available")
|
|
125
|
+
if code is not None and code >= 500:
|
|
126
|
+
return ChatError("Gemini is unavailable")
|
|
127
|
+
if code == 400 and looks_like_context_limit(detail):
|
|
128
|
+
return ChatError("the conversation is too long for this model")
|
|
129
|
+
if "timed out" in detail.lower() or "timeout" in detail.lower():
|
|
130
|
+
return ChatError("Gemini request timed out")
|
|
131
|
+
return ChatError(one_line(exc))
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Grok provider. Not part of the public package API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Generator, Iterator
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
|
|
9
|
+
import grpc
|
|
10
|
+
from xai_sdk import Client
|
|
11
|
+
from xai_sdk.chat import assistant, system, user
|
|
12
|
+
from xai_sdk.proto import chat_pb2
|
|
13
|
+
|
|
14
|
+
from .catalog import CATALOG
|
|
15
|
+
from .errors import ChatError, looks_like_context_limit, one_line
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GrokProvider:
|
|
19
|
+
"""Chat through the official xAI SDK."""
|
|
20
|
+
|
|
21
|
+
mode = CATALOG["grok"].mode
|
|
22
|
+
supports_stream = True
|
|
23
|
+
|
|
24
|
+
def __init__(self, timeout: float) -> None:
|
|
25
|
+
self.timeout = timeout
|
|
26
|
+
|
|
27
|
+
def chat(
|
|
28
|
+
self,
|
|
29
|
+
messages: list[dict[str, str]],
|
|
30
|
+
model: str,
|
|
31
|
+
system_prompt: str,
|
|
32
|
+
) -> str:
|
|
33
|
+
payload = _messages(messages, system_prompt)
|
|
34
|
+
with _session(self.timeout, model) as client:
|
|
35
|
+
chat = client.chat.create(
|
|
36
|
+
model=model,
|
|
37
|
+
messages=payload,
|
|
38
|
+
store_messages=False,
|
|
39
|
+
)
|
|
40
|
+
response = chat.sample()
|
|
41
|
+
try:
|
|
42
|
+
content = response.content
|
|
43
|
+
except AttributeError as exc:
|
|
44
|
+
raise ChatError("the provider returned an invalid response") from exc
|
|
45
|
+
if content is None or not str(content).strip():
|
|
46
|
+
raise ChatError("the provider returned an invalid response")
|
|
47
|
+
return str(content)
|
|
48
|
+
|
|
49
|
+
def stream(
|
|
50
|
+
self,
|
|
51
|
+
messages: list[dict[str, str]],
|
|
52
|
+
model: str,
|
|
53
|
+
system_prompt: str,
|
|
54
|
+
) -> Iterator[str]:
|
|
55
|
+
payload = _messages(messages, system_prompt)
|
|
56
|
+
with _session(self.timeout, model) as client:
|
|
57
|
+
chat = client.chat.create(
|
|
58
|
+
model=model,
|
|
59
|
+
messages=payload,
|
|
60
|
+
store_messages=False,
|
|
61
|
+
)
|
|
62
|
+
for _response, chunk in chat.stream():
|
|
63
|
+
try:
|
|
64
|
+
content = chunk.content
|
|
65
|
+
except AttributeError as exc:
|
|
66
|
+
raise ChatError("the provider returned an invalid response") from exc
|
|
67
|
+
if content:
|
|
68
|
+
yield str(content)
|
|
69
|
+
|
|
70
|
+
def list_models(self) -> list[str]:
|
|
71
|
+
with _session(self.timeout, "") as client:
|
|
72
|
+
names: list[str] = []
|
|
73
|
+
for model in client.models.list_language_models():
|
|
74
|
+
name = getattr(model, "name", None)
|
|
75
|
+
if name is None or not str(name).strip():
|
|
76
|
+
raise ChatError("the provider returned an invalid response")
|
|
77
|
+
names.append(str(name))
|
|
78
|
+
return names
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _messages(
|
|
82
|
+
messages: list[dict[str, str]],
|
|
83
|
+
system_prompt: str,
|
|
84
|
+
) -> list[chat_pb2.Message]:
|
|
85
|
+
payload: list[chat_pb2.Message] = [system(system_prompt)]
|
|
86
|
+
for message in messages:
|
|
87
|
+
content = message["content"]
|
|
88
|
+
role = message["role"]
|
|
89
|
+
if role == "user":
|
|
90
|
+
payload.append(user(content))
|
|
91
|
+
elif role == "assistant":
|
|
92
|
+
payload.append(assistant(content))
|
|
93
|
+
else:
|
|
94
|
+
raise ChatError("the provider returned an invalid response")
|
|
95
|
+
return payload
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _client(timeout: float) -> Client:
|
|
99
|
+
key = os.environ.get("XAI_API_KEY", "").strip()
|
|
100
|
+
if not key:
|
|
101
|
+
raise ChatError("XAI_API_KEY is not configured")
|
|
102
|
+
return Client(
|
|
103
|
+
api_key=key,
|
|
104
|
+
timeout=timeout,
|
|
105
|
+
channel_options=[("grpc.enable_retries", 0)],
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@contextmanager
|
|
110
|
+
def _session(timeout: float, model: str) -> Generator[Client, None, None]:
|
|
111
|
+
client = _client(timeout)
|
|
112
|
+
try:
|
|
113
|
+
yield client
|
|
114
|
+
except ChatError:
|
|
115
|
+
raise
|
|
116
|
+
except grpc.RpcError as exc:
|
|
117
|
+
raise _translate(exc, model) from None
|
|
118
|
+
except OSError:
|
|
119
|
+
raise ChatError("network error talking to Grok") from None
|
|
120
|
+
except Exception as exc:
|
|
121
|
+
raise ChatError(one_line(exc)) from None
|
|
122
|
+
finally:
|
|
123
|
+
client.close()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _translate(exc: grpc.RpcError, model: str) -> ChatError:
|
|
127
|
+
code = exc.code()
|
|
128
|
+
if code in (grpc.StatusCode.UNAUTHENTICATED, grpc.StatusCode.PERMISSION_DENIED):
|
|
129
|
+
return ChatError("Grok authentication failed")
|
|
130
|
+
if code == grpc.StatusCode.RESOURCE_EXHAUSTED:
|
|
131
|
+
return ChatError("Grok rate limit reached")
|
|
132
|
+
if code == grpc.StatusCode.DEADLINE_EXCEEDED:
|
|
133
|
+
return ChatError("Grok request timed out")
|
|
134
|
+
if code == grpc.StatusCode.NOT_FOUND:
|
|
135
|
+
return ChatError(f"model '{model}' is not available")
|
|
136
|
+
if code == grpc.StatusCode.INVALID_ARGUMENT and looks_like_context_limit(str(exc)):
|
|
137
|
+
return ChatError("the conversation is too long for this model")
|
|
138
|
+
if code in (grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.INTERNAL):
|
|
139
|
+
return ChatError("Grok is unavailable")
|
|
140
|
+
return ChatError(one_line(exc))
|