mcdakit 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.
@@ -0,0 +1,438 @@
1
+ """Ready-made ``ask`` callables for the common language-model providers.
2
+
3
+ :mod:`mcdakit.ai` takes any ``Callable[[str], str]``, which is deliberately the
4
+ smallest interface that can work and commits the package to no vendor. The
5
+ cost of that generality is boilerplate: every user writes the same adapter,
6
+ looks up where their SDK buries the reply text, and gets no retry when a rate
7
+ limit arrives mid-run.
8
+
9
+ These adapters remove that work without spending the package's independence.
10
+ **No provider SDK is required.** Each adapter speaks the vendor's HTTP API
11
+ directly through :mod:`urllib` from the standard library, so
12
+
13
+ pip install mcdakit
14
+
15
+ is enough to reach OpenAI, Anthropic, Google or a local model. NumPy remains
16
+ the only runtime dependency. Where a vendor SDK *is* installed it is not used:
17
+ one code path is easier to trust than two that must agree.
18
+
19
+ .. code-block:: python
20
+
21
+ from mcdakit.ai import propose_criteria
22
+ from mcdakit.ai_providers import anthropic, ollama
23
+
24
+ ask = anthropic() # reads ANTHROPIC_API_KEY
25
+ ask = ollama("llama3") # local, no key, nothing leaves the machine
26
+ proposal = propose_criteria("choosing a supplier", ask=ask)
27
+
28
+ Every adapter returns a plain function, so it can be wrapped, logged, cached
29
+ or replaced by a fixture in a test exactly like a hand-written one.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ import os
36
+ import pathlib
37
+ import time
38
+ import urllib.error
39
+ import urllib.request
40
+ from collections.abc import Callable, Mapping
41
+
42
+ from .types import McdaError
43
+
44
+ __all__ = [
45
+ "ProviderError",
46
+ "anthropic",
47
+ "google",
48
+ "load_env",
49
+ "ollama",
50
+ "openai",
51
+ "openai_compatible",
52
+ ]
53
+
54
+ #: Status codes worth retrying: a rate limit, and the transient server errors.
55
+ #: A 400 or 401 is a mistake in the request and will fail identically however
56
+ #: many times it is sent.
57
+ _RETRYABLE = frozenset({408, 409, 429, 500, 502, 503, 504})
58
+
59
+ DEFAULT_TIMEOUT = 60.0
60
+ DEFAULT_RETRIES = 3
61
+
62
+
63
+ class ProviderError(McdaError):
64
+ """A provider could not be reached, or refused the request."""
65
+
66
+
67
+ def load_env(path: str = ".env", *, override: bool = False) -> dict:
68
+ """Read ``KEY=value`` lines from a file into the environment.
69
+
70
+ Keeping API keys in a ``.env`` file rather than in source is the usual
71
+ practice, and the parsing is short enough that requiring ``python-dotenv``
72
+ for it would cost more than it saves. Searches the given path, then each
73
+ parent directory, so it works from anywhere in a project.
74
+
75
+ .. code-block:: python
76
+
77
+ from mcdakit.ai_providers import anthropic, load_env
78
+
79
+ load_env() # reads ./.env, or the nearest one above it
80
+ ask = anthropic() # ANTHROPIC_API_KEY now set
81
+
82
+ Understands ``KEY=value``, ``export KEY=value``, quoted values, blank
83
+ lines and ``#`` comments. A variable already set in the environment is
84
+ left alone unless ``override`` is true — the real environment should win
85
+ over a file in a checkout, or deploying becomes surprising.
86
+
87
+ Returns the names it set, and their values, so a caller can see what came
88
+ from the file. Returns an empty mapping when no file is found: a missing
89
+ ``.env`` is the normal case in production, not an error.
90
+
91
+ **Never commit the file.** ``.env`` is in this project's ``.gitignore``
92
+ for that reason; do the same in yours.
93
+ """
94
+ start = pathlib.Path(path).expanduser()
95
+ if start.is_absolute() or start.parent != pathlib.Path("."):
96
+ candidates = [start]
97
+ else:
98
+ here = pathlib.Path.cwd()
99
+ candidates = [d / start.name for d in (here, *here.parents)]
100
+
101
+ found = next((c for c in candidates if c.is_file()), None)
102
+ if found is None:
103
+ return {}
104
+
105
+ loaded: dict = {}
106
+ for raw in found.read_text(encoding="utf-8").splitlines():
107
+ line = raw.strip()
108
+ if not line or line.startswith("#") or "=" not in line:
109
+ continue
110
+ name, _, value = line.partition("=")
111
+ name = name.removeprefix("export ").strip()
112
+ if not name:
113
+ continue
114
+ value = value.strip()
115
+ # Strip one matching pair of surrounding quotes, so a value with
116
+ # spaces or a trailing comment marker survives intact.
117
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
118
+ value = value[1:-1]
119
+ if override or name not in os.environ:
120
+ os.environ[name] = value
121
+ loaded[name] = value
122
+ return loaded
123
+
124
+
125
+ def _require_key(explicit: str | None, variable: str, provider: str) -> str:
126
+ """Resolve an API key, and say plainly when there is none.
127
+
128
+ A missing key otherwise surfaces as a 401 from the vendor, which reads as
129
+ though the key were wrong rather than absent.
130
+ """
131
+ key = explicit or os.environ.get(variable)
132
+ if not key:
133
+ raise ProviderError(
134
+ f"No API key for {provider}. Set the {variable} environment "
135
+ f"variable, or pass api_key= explicitly. For a local model that "
136
+ f"needs no key, use ollama() or openai_compatible()."
137
+ )
138
+ return key
139
+
140
+
141
+ def _post(
142
+ url: str,
143
+ payload: Mapping,
144
+ headers: Mapping[str, str],
145
+ *,
146
+ timeout: float,
147
+ retries: int,
148
+ provider: str,
149
+ ) -> dict:
150
+ """POST JSON and return the decoded reply, retrying what is worth retrying.
151
+
152
+ Backoff is exponential and honours ``Retry-After`` when the provider sends
153
+ one, since a server's own estimate beats a guess. The final failure is
154
+ raised with the provider's message attached: debugging a rate limit
155
+ without knowing it was a rate limit is needlessly hard.
156
+ """
157
+ if retries < 1:
158
+ raise ProviderError(
159
+ f"retries must be at least 1; got {retries}. A request that is "
160
+ f"never attempted cannot succeed."
161
+ )
162
+
163
+ body = json.dumps(payload).encode("utf-8")
164
+ request = urllib.request.Request(
165
+ url,
166
+ data=body,
167
+ headers={"Content-Type": "application/json", **headers},
168
+ method="POST",
169
+ )
170
+
171
+ last: Exception | None = None
172
+ for attempt in range(retries):
173
+ try:
174
+ with urllib.request.urlopen(request, timeout=timeout) as response:
175
+ return json.loads(response.read().decode("utf-8"))
176
+ except urllib.error.HTTPError as exc:
177
+ detail = exc.read().decode("utf-8", "replace")[:400]
178
+ if exc.code not in _RETRYABLE or attempt == retries - 1:
179
+ raise ProviderError(
180
+ f"{provider} returned HTTP {exc.code}: {detail}"
181
+ ) from exc
182
+ last = exc
183
+ delay = _backoff(exc, attempt)
184
+ except urllib.error.URLError as exc:
185
+ if attempt == retries - 1:
186
+ raise ProviderError(
187
+ f"Could not reach {provider}: {exc.reason}. For a local "
188
+ f"model, check the server is running."
189
+ ) from exc
190
+ last = exc
191
+ delay = 2.0**attempt
192
+ time.sleep(delay)
193
+
194
+ # Unreachable: the loop runs at least once, and its final iteration either
195
+ # returns or raises. Kept as a guard against a future edit to that logic.
196
+ raise ProviderError( # pragma: no cover
197
+ f"{provider} failed after {retries} attempts: {last}"
198
+ )
199
+
200
+
201
+ def _backoff(error: urllib.error.HTTPError, attempt: int) -> float:
202
+ """Seconds to wait, preferring the provider's own Retry-After."""
203
+ retry_after = error.headers.get("Retry-After") if error.headers else None
204
+ if retry_after:
205
+ try:
206
+ return min(float(retry_after), 60.0)
207
+ except ValueError:
208
+ pass
209
+ return 2.0**attempt
210
+
211
+
212
+ def _dig(payload: dict, path: tuple, provider: str) -> str:
213
+ """Walk a reply to the text, and report the shape when it is not there.
214
+
215
+ Providers change response shapes between versions, and an ``IndexError``
216
+ from deep inside an adapter tells the caller nothing about which provider
217
+ returned what.
218
+ """
219
+ node = payload
220
+ for step in path:
221
+ try:
222
+ node = node[step]
223
+ except (KeyError, IndexError, TypeError) as exc:
224
+ raise ProviderError(
225
+ f"Unexpected reply shape from {provider}: could not read "
226
+ f"{'.'.join(map(str, path))}. Got: {json.dumps(payload)[:300]}"
227
+ ) from exc
228
+ if not isinstance(node, str):
229
+ raise ProviderError(
230
+ f"Expected text from {provider}, got {type(node).__name__}."
231
+ )
232
+ return node
233
+
234
+
235
+ def openai(
236
+ model: str = "gpt-4o",
237
+ *,
238
+ api_key: str | None = None,
239
+ base_url: str = "https://api.openai.com/v1",
240
+ temperature: float = 0.0,
241
+ max_tokens: int = 2048,
242
+ timeout: float = DEFAULT_TIMEOUT,
243
+ retries: int = DEFAULT_RETRIES,
244
+ ) -> Callable[[str], str]:
245
+ """An ``ask`` callable backed by OpenAI's chat completions API.
246
+
247
+ Reads ``OPENAI_API_KEY`` unless ``api_key`` is given.
248
+
249
+ ``temperature`` defaults to 0. The module asks a model the same question
250
+ more than once to measure whether it is consistent, and a temperature
251
+ above zero would make the replies differ for reasons that have nothing to
252
+ do with the model's confidence.
253
+ """
254
+ key = _require_key(api_key, "OPENAI_API_KEY", "OpenAI")
255
+ return openai_compatible(
256
+ model=model,
257
+ base_url=base_url,
258
+ api_key=key,
259
+ temperature=temperature,
260
+ max_tokens=max_tokens,
261
+ timeout=timeout,
262
+ retries=retries,
263
+ provider="OpenAI",
264
+ )
265
+
266
+
267
+ def openai_compatible(
268
+ model: str,
269
+ base_url: str,
270
+ *,
271
+ api_key: str | None = None,
272
+ temperature: float = 0.0,
273
+ max_tokens: int = 2048,
274
+ timeout: float = DEFAULT_TIMEOUT,
275
+ retries: int = DEFAULT_RETRIES,
276
+ provider: str = "OpenAI-compatible server",
277
+ ) -> Callable[[str], str]:
278
+ """An ``ask`` callable for any server exposing ``/chat/completions``.
279
+
280
+ That interface has become the common denominator, so this one adapter
281
+ reaches vLLM, LM Studio, llama.cpp's server, Together, Groq, OpenRouter,
282
+ DeepSeek, Mistral and most others — including models running on your own
283
+ machine, where ``api_key`` is usually unnecessary.
284
+
285
+ .. code-block:: python
286
+
287
+ ask = openai_compatible("mistral-7b", "http://localhost:8000/v1")
288
+ """
289
+ url = base_url.rstrip("/") + "/chat/completions"
290
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
291
+
292
+ def ask(prompt: str) -> str:
293
+ payload = {
294
+ "model": model,
295
+ "messages": [{"role": "user", "content": prompt}],
296
+ "temperature": temperature,
297
+ "max_tokens": max_tokens,
298
+ }
299
+ reply = _post(
300
+ url,
301
+ payload,
302
+ headers,
303
+ timeout=timeout,
304
+ retries=retries,
305
+ provider=provider,
306
+ )
307
+ return _dig(reply, ("choices", 0, "message", "content"), provider)
308
+
309
+ return ask
310
+
311
+
312
+ def anthropic(
313
+ model: str = "claude-sonnet-5",
314
+ *,
315
+ api_key: str | None = None,
316
+ base_url: str = "https://api.anthropic.com/v1",
317
+ temperature: float = 0.0,
318
+ max_tokens: int = 2048,
319
+ timeout: float = DEFAULT_TIMEOUT,
320
+ retries: int = DEFAULT_RETRIES,
321
+ ) -> Callable[[str], str]:
322
+ """An ``ask`` callable backed by Anthropic's messages API.
323
+
324
+ Reads ``ANTHROPIC_API_KEY`` unless ``api_key`` is given.
325
+ """
326
+ key = _require_key(api_key, "ANTHROPIC_API_KEY", "Anthropic")
327
+ url = base_url.rstrip("/") + "/messages"
328
+ headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
329
+
330
+ def ask(prompt: str) -> str:
331
+ payload = {
332
+ "model": model,
333
+ "max_tokens": max_tokens,
334
+ "temperature": temperature,
335
+ "messages": [{"role": "user", "content": prompt}],
336
+ }
337
+ reply = _post(
338
+ url,
339
+ payload,
340
+ headers,
341
+ timeout=timeout,
342
+ retries=retries,
343
+ provider="Anthropic",
344
+ )
345
+ return _dig(reply, ("content", 0, "text"), "Anthropic")
346
+
347
+ return ask
348
+
349
+
350
+ def google(
351
+ model: str = "gemini-2.0-flash",
352
+ *,
353
+ api_key: str | None = None,
354
+ base_url: str = "https://generativelanguage.googleapis.com/v1beta",
355
+ temperature: float = 0.0,
356
+ max_tokens: int = 2048,
357
+ timeout: float = DEFAULT_TIMEOUT,
358
+ retries: int = DEFAULT_RETRIES,
359
+ ) -> Callable[[str], str]:
360
+ """An ``ask`` callable backed by Google's Gemini API.
361
+
362
+ Reads ``GOOGLE_API_KEY``, then ``GEMINI_API_KEY``, unless ``api_key`` is
363
+ given.
364
+ """
365
+ key = (
366
+ api_key or os.environ.get("GOOGLE_API_KEY") or os.environ.get("GEMINI_API_KEY")
367
+ )
368
+ key = _require_key(key, "GOOGLE_API_KEY", "Google")
369
+ url = f"{base_url.rstrip('/')}/models/{model}:generateContent"
370
+ headers = {"x-goog-api-key": key}
371
+
372
+ def ask(prompt: str) -> str:
373
+ payload = {
374
+ "contents": [{"parts": [{"text": prompt}]}],
375
+ "generationConfig": {
376
+ "temperature": temperature,
377
+ "maxOutputTokens": max_tokens,
378
+ },
379
+ }
380
+ reply = _post(
381
+ url,
382
+ payload,
383
+ headers,
384
+ timeout=timeout,
385
+ retries=retries,
386
+ provider="Google",
387
+ )
388
+ return _dig(
389
+ reply,
390
+ ("candidates", 0, "content", "parts", 0, "text"),
391
+ "Google",
392
+ )
393
+
394
+ return ask
395
+
396
+
397
+ def ollama(
398
+ model: str = "llama3",
399
+ *,
400
+ base_url: str = "http://localhost:11434",
401
+ temperature: float = 0.0,
402
+ timeout: float = 120.0,
403
+ retries: int = DEFAULT_RETRIES,
404
+ ) -> Callable[[str], str]:
405
+ """An ``ask`` callable backed by a local Ollama server.
406
+
407
+ No API key and no network: the problem description, the criteria and the
408
+ measurements stay on the machine. That matters for decisions involving
409
+ commercially sensitive data, which is a large share of real MCDA work.
410
+
411
+ The timeout is longer than the hosted default because a local model on
412
+ CPU is markedly slower than an API call.
413
+
414
+ .. code-block:: python
415
+
416
+ ask = ollama("llama3")
417
+ ask = ollama("mixtral", base_url="http://gpu-box:11434")
418
+ """
419
+ url = base_url.rstrip("/") + "/api/generate"
420
+
421
+ def ask(prompt: str) -> str:
422
+ payload = {
423
+ "model": model,
424
+ "prompt": prompt,
425
+ "stream": False,
426
+ "options": {"temperature": temperature},
427
+ }
428
+ reply = _post(
429
+ url,
430
+ payload,
431
+ {},
432
+ timeout=timeout,
433
+ retries=retries,
434
+ provider="Ollama",
435
+ )
436
+ return _dig(reply, ("response",), "Ollama")
437
+
438
+ return ask