margin-core 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,34 @@
1
+ """Request/response helpers for the OpenAI Chat Completions wire format.
2
+
3
+ Shared by the OpenAI client and by local servers that expose an OpenAI-compatible API
4
+ (Ollama, LM Studio, llama.cpp, vLLM).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from margin_core.errors import LLMError
12
+ from margin_core.llm.base import LLMResponse, Message
13
+
14
+
15
+ def chat_messages(messages: list[Message], system: str | None) -> list[dict[str, str]]:
16
+ chat: list[dict[str, str]] = []
17
+ if system:
18
+ chat.append({"role": "system", "content": system})
19
+ chat.extend(m.model_dump() for m in messages)
20
+ return chat
21
+
22
+
23
+ def parse_chat_completion(data: dict[str, Any], default_model: str, provider: str) -> LLMResponse:
24
+ try:
25
+ text = data["choices"][0]["message"].get("content") or ""
26
+ usage = data.get("usage") or {}
27
+ return LLMResponse(
28
+ text=str(text),
29
+ model=str(data.get("model", default_model)),
30
+ input_tokens=int(usage.get("prompt_tokens", 0)),
31
+ output_tokens=int(usage.get("completion_tokens", 0)),
32
+ )
33
+ except (KeyError, IndexError, TypeError, AttributeError) as exc:
34
+ raise LLMError(f"Unexpected {provider} response: {exc}") from exc
@@ -0,0 +1,42 @@
1
+ """Shared HTTP helper for REST-based LLM providers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from margin_core.errors import LLMError, TransientLLMError
10
+
11
+
12
+ async def post_json(
13
+ url: str,
14
+ *,
15
+ headers: dict[str, str],
16
+ payload: dict[str, Any],
17
+ timeout_s: float,
18
+ client: httpx.AsyncClient | None = None,
19
+ ) -> dict[str, Any]:
20
+ """POST JSON and return the decoded object, mapping failures onto LLM errors."""
21
+ try:
22
+ if client is not None:
23
+ response = await client.post(url, headers=headers, json=payload, timeout=timeout_s)
24
+ else:
25
+ async with httpx.AsyncClient(timeout=timeout_s) as owned:
26
+ response = await owned.post(url, headers=headers, json=payload)
27
+ except httpx.TimeoutException as exc:
28
+ raise TransientLLMError(f"Request timed out: {exc}") from exc
29
+ except httpx.TransportError as exc:
30
+ raise TransientLLMError(f"Network error: {exc}") from exc
31
+
32
+ if response.status_code == 429 or response.status_code >= 500:
33
+ raise TransientLLMError(f"HTTP {response.status_code}: {response.text[:500]}")
34
+ if response.status_code >= 400:
35
+ raise LLMError(f"HTTP {response.status_code}: {response.text[:500]}")
36
+ try:
37
+ data = response.json()
38
+ except ValueError as exc:
39
+ raise LLMError(f"Invalid JSON from provider: {response.text[:200]}") from exc
40
+ if not isinstance(data, dict):
41
+ raise LLMError("Unexpected response shape from provider")
42
+ return data
@@ -0,0 +1,80 @@
1
+ """Anthropic Messages API client (REST via httpx)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, ClassVar, Unpack
7
+
8
+ import httpx
9
+
10
+ from margin_core.errors import LLMError
11
+ from margin_core.llm._http import post_json
12
+ from margin_core.llm.base import LLMClient, LLMClientOptions, LLMResponse, Message
13
+
14
+ DEFAULT_BASE_URL = "https://api.anthropic.com"
15
+ API_VERSION = "2023-06-01"
16
+
17
+
18
+ class AnthropicLLM(LLMClient):
19
+ """Client for the Anthropic Messages API. Reads ``ANTHROPIC_API_KEY`` if no key is given."""
20
+
21
+ provider: ClassVar[str] = "anthropic"
22
+
23
+ def __init__(
24
+ self,
25
+ model: str,
26
+ *,
27
+ api_key: str | None = None,
28
+ base_url: str = DEFAULT_BASE_URL,
29
+ http_client: httpx.AsyncClient | None = None,
30
+ **options: Unpack[LLMClientOptions],
31
+ ) -> None:
32
+ super().__init__(model, **options)
33
+ key = api_key or os.environ.get("ANTHROPIC_API_KEY")
34
+ if not key:
35
+ raise LLMError("Anthropic API key missing: set ANTHROPIC_API_KEY or pass api_key")
36
+ self._api_key = key
37
+ self._url = f"{base_url.rstrip('/')}/v1/messages"
38
+ self._http_client = http_client
39
+
40
+ async def _complete_raw(
41
+ self,
42
+ messages: list[Message],
43
+ system: str | None,
44
+ max_tokens: int,
45
+ temperature: float | None,
46
+ json_schema: dict[str, Any] | None = None,
47
+ ) -> LLMResponse:
48
+ payload: dict[str, Any] = {
49
+ "model": self.model,
50
+ "max_tokens": max_tokens,
51
+ "messages": [m.model_dump() for m in messages],
52
+ }
53
+ if system:
54
+ payload["system"] = system
55
+ if temperature is not None:
56
+ payload["temperature"] = temperature
57
+ data = await post_json(
58
+ self._url,
59
+ headers={
60
+ "x-api-key": self._api_key,
61
+ "anthropic-version": API_VERSION,
62
+ "content-type": "application/json",
63
+ },
64
+ payload=payload,
65
+ timeout_s=self.timeout_s,
66
+ client=self._http_client,
67
+ )
68
+ try:
69
+ text = "".join(
70
+ block.get("text", "") for block in data["content"] if block.get("type") == "text"
71
+ )
72
+ usage = data.get("usage", {})
73
+ return LLMResponse(
74
+ text=text,
75
+ model=str(data.get("model", self.model)),
76
+ input_tokens=int(usage.get("input_tokens", 0)),
77
+ output_tokens=int(usage.get("output_tokens", 0)),
78
+ )
79
+ except (KeyError, TypeError, AttributeError) as exc:
80
+ raise LLMError(f"Unexpected Anthropic response: {exc}") from exc
@@ -0,0 +1,338 @@
1
+ """Provider-agnostic LLM client with retries, timeouts, cost tracking and a budget cap.
2
+
3
+ A client is long-lived and may be shared. Each agent run talks to a :class:`LLMSession`
4
+ opened from it (see :meth:`LLMClient.session`), so usage, warnings and the budget are
5
+ tracked per run while the client keeps lifetime totals.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ from abc import ABC, abstractmethod
13
+ from collections.abc import Awaitable, Callable, Sequence
14
+ from typing import Any, ClassVar, Literal, TypedDict, TypeVar
15
+
16
+ from pydantic import BaseModel, Field, ValidationError
17
+
18
+ from margin_core.errors import BudgetExceededError, LLMError, TransientLLMError
19
+ from margin_core.llm.pricing import ModelPricing, lookup_pricing
20
+ from margin_core.logging import get_logger
21
+ from margin_core.models import TokenUsage
22
+
23
+ T = TypeVar("T", bound=BaseModel)
24
+ R = TypeVar("R")
25
+
26
+ logger = get_logger("llm")
27
+
28
+ CHARS_PER_TOKEN_ESTIMATE = 4
29
+
30
+
31
+ class Message(BaseModel):
32
+ """A chat message."""
33
+
34
+ role: Literal["user", "assistant"]
35
+ content: str
36
+
37
+
38
+ class LLMResponse(BaseModel):
39
+ """A completed LLM call."""
40
+
41
+ text: str
42
+ model: str
43
+ input_tokens: int = 0
44
+ output_tokens: int = 0
45
+ cost_usd: float = 0.0
46
+ warnings: list[str] = Field(
47
+ default_factory=list, description="Problems noticed by the provider, e.g. truncation."
48
+ )
49
+
50
+
51
+ class LLMClientOptions(TypedDict, total=False):
52
+ """Common keyword options accepted by every client constructor."""
53
+
54
+ max_cost_usd: float | None
55
+ timeout_s: float
56
+ max_retries: int
57
+ backoff_base_s: float
58
+ pricing: ModelPricing | None
59
+
60
+
61
+ Prompt = str | Sequence[Message]
62
+
63
+
64
+ def _normalize(prompt: Prompt) -> list[Message]:
65
+ if isinstance(prompt, str):
66
+ return [Message(role="user", content=prompt)]
67
+ return list(prompt)
68
+
69
+
70
+ def extract_json(text: str) -> str:
71
+ """Extract a JSON object/array from an LLM reply (handles code fences and prose)."""
72
+ stripped = text.strip()
73
+ if stripped.startswith("```"):
74
+ stripped = stripped.split("\n", 1)[1] if "\n" in stripped else ""
75
+ if stripped.rstrip().endswith("```"):
76
+ stripped = stripped.rstrip()[:-3]
77
+ stripped = stripped.strip()
78
+ try:
79
+ json.loads(stripped)
80
+ return stripped
81
+ except json.JSONDecodeError:
82
+ pass
83
+ for open_ch, close_ch in (("{", "}"), ("[", "]")):
84
+ start, end = stripped.find(open_ch), stripped.rfind(close_ch)
85
+ if start != -1 and end > start:
86
+ candidate = stripped[start : end + 1]
87
+ try:
88
+ json.loads(candidate)
89
+ return candidate
90
+ except json.JSONDecodeError:
91
+ continue
92
+ raise ValueError("No valid JSON found in model output")
93
+
94
+
95
+ class LLMClient(ABC):
96
+ """Base class for LLM clients.
97
+
98
+ Subclasses implement :meth:`_complete_raw`; this class adds retries with exponential
99
+ backoff, per-call timeouts, usage/cost accounting, and a hard budget cap.
100
+ """
101
+
102
+ provider: ClassVar[str]
103
+
104
+ def __init__(
105
+ self,
106
+ model: str,
107
+ *,
108
+ max_cost_usd: float | None = None,
109
+ timeout_s: float = 60.0,
110
+ max_retries: int = 3,
111
+ backoff_base_s: float = 1.0,
112
+ pricing: ModelPricing | None = None,
113
+ ) -> None:
114
+ self.model = model
115
+ self.max_cost_usd = max_cost_usd
116
+ self.timeout_s = timeout_s
117
+ self.max_retries = max_retries
118
+ self.backoff_base_s = backoff_base_s
119
+ self.pricing = pricing or lookup_pricing(self.provider, model)
120
+ self.parent: LLMClient | None = None
121
+ self._usage = TokenUsage()
122
+ self._warnings: list[str] = []
123
+
124
+ def session(self, *, max_cost_usd: float | None = None) -> LLMSession:
125
+ """Open a per-run view of this client with its own usage, warnings and budget.
126
+
127
+ Calls through the session also count toward this client (and its budget, if any).
128
+ """
129
+ return LLMSession(self, max_cost_usd=max_cost_usd)
130
+
131
+ async def context_window(self) -> int | None:
132
+ """The model's context window in tokens, if the provider can tell; else ``None``."""
133
+ return None
134
+
135
+ # ---- accounting -----------------------------------------------------------------
136
+
137
+ @property
138
+ def usage(self) -> TokenUsage:
139
+ """A snapshot of cumulative usage for this client."""
140
+ return self._usage.model_copy()
141
+
142
+ @property
143
+ def remaining_budget_usd(self) -> float | None:
144
+ if self.max_cost_usd is None:
145
+ return None
146
+ return max(0.0, self.max_cost_usd - self._usage.cost_usd)
147
+
148
+ @property
149
+ def warnings(self) -> list[str]:
150
+ """Distinct provider warnings collected so far, in order of first appearance."""
151
+ return list(self._warnings)
152
+
153
+ def _record(self, usage: TokenUsage, warnings: Sequence[str]) -> None:
154
+ self._usage = self._usage + usage
155
+ for warning in warnings:
156
+ if warning not in self._warnings:
157
+ self._warnings.append(warning)
158
+ if self.parent is not None:
159
+ self.parent._record(usage, warnings)
160
+
161
+ def estimate_cost(
162
+ self, messages: Sequence[Message], system: str | None, max_tokens: int
163
+ ) -> float:
164
+ """Worst-case cost estimate for a call (assumes the full ``max_tokens`` output)."""
165
+ chars = sum(len(m.content) for m in messages) + len(system or "")
166
+ return self.pricing.cost(chars // CHARS_PER_TOKEN_ESTIMATE + 1, max_tokens)
167
+
168
+ def _check_budget(
169
+ self, messages: Sequence[Message], system: str | None, max_tokens: int
170
+ ) -> None:
171
+ if self.max_cost_usd is None:
172
+ return
173
+ estimate = self.estimate_cost(messages, system, max_tokens)
174
+ if self._usage.cost_usd + estimate > self.max_cost_usd:
175
+ raise BudgetExceededError(
176
+ f"LLM budget of ${self.max_cost_usd:.4f} would be exceeded "
177
+ f"(spent ${self._usage.cost_usd:.4f}, next call up to ${estimate:.4f})"
178
+ )
179
+
180
+ def _check_budgets(
181
+ self, messages: Sequence[Message], system: str | None, max_tokens: int
182
+ ) -> None:
183
+ self._check_budget(messages, system, max_tokens)
184
+ if self.parent is not None:
185
+ self.parent._check_budgets(messages, system, max_tokens)
186
+
187
+ # ---- public API -----------------------------------------------------------------
188
+
189
+ async def complete(
190
+ self,
191
+ prompt: Prompt,
192
+ *,
193
+ system: str | None = None,
194
+ max_tokens: int = 1024,
195
+ temperature: float | None = 0.0,
196
+ json_schema: dict[str, Any] | None = None,
197
+ ) -> LLMResponse:
198
+ """Run a text completion.
199
+
200
+ ``json_schema`` asks providers that support constrained decoding to emit JSON matching
201
+ it; providers without that support ignore it.
202
+ """
203
+ messages = _normalize(prompt)
204
+ self._check_budgets(messages, system, max_tokens)
205
+ response = await self._with_retries(
206
+ lambda: self._complete_raw(messages, system, max_tokens, temperature, json_schema)
207
+ )
208
+ cost = self.pricing.cost(response.input_tokens, response.output_tokens)
209
+ response = response.model_copy(update={"cost_usd": cost})
210
+ self._record(
211
+ TokenUsage(
212
+ llm_calls=1,
213
+ input_tokens=response.input_tokens,
214
+ output_tokens=response.output_tokens,
215
+ cost_usd=cost,
216
+ ),
217
+ response.warnings,
218
+ )
219
+ return response
220
+
221
+ async def complete_structured(
222
+ self,
223
+ schema: type[T],
224
+ prompt: Prompt,
225
+ *,
226
+ system: str | None = None,
227
+ max_tokens: int = 2048,
228
+ temperature: float | None = 0.0,
229
+ max_repair_attempts: int = 1,
230
+ ) -> T:
231
+ """Run a completion whose output must validate against ``schema``.
232
+
233
+ On invalid output the model is shown the error and asked to repair its reply,
234
+ up to ``max_repair_attempts`` times.
235
+ """
236
+ json_schema = schema.model_json_schema()
237
+ instructions = (
238
+ "Respond with a single JSON object that validates against this JSON Schema. "
239
+ "Output only the JSON, with no prose and no code fences.\n"
240
+ f"JSON Schema:\n{json.dumps(json_schema)}"
241
+ )
242
+ full_system = f"{system}\n\n{instructions}" if system else instructions
243
+ messages = _normalize(prompt)
244
+ last_error: Exception | None = None
245
+ for _attempt in range(max_repair_attempts + 1):
246
+ response = await self.complete(
247
+ messages,
248
+ system=full_system,
249
+ max_tokens=max_tokens,
250
+ temperature=temperature,
251
+ json_schema=json_schema,
252
+ )
253
+ try:
254
+ return schema.model_validate_json(extract_json(response.text))
255
+ except (ValidationError, ValueError) as exc:
256
+ last_error = exc
257
+ messages = [
258
+ *messages,
259
+ Message(role="assistant", content=response.text),
260
+ Message(
261
+ role="user",
262
+ content=(
263
+ "Your previous reply did not validate against the schema. "
264
+ f"Error: {exc}\nReply again with only valid JSON."
265
+ ),
266
+ ),
267
+ ]
268
+ raise LLMError(f"Model output failed schema validation: {last_error}")
269
+
270
+ # ---- internals ------------------------------------------------------------------
271
+
272
+ async def _with_retries(self, call: Callable[[], Awaitable[R]]) -> R:
273
+ attempt = 0
274
+ while True:
275
+ try:
276
+ return await asyncio.wait_for(call(), timeout=self.timeout_s)
277
+ except (TransientLLMError, TimeoutError) as exc:
278
+ if attempt >= self.max_retries:
279
+ raise TransientLLMError(
280
+ f"LLM call failed after {attempt + 1} attempts: {exc}"
281
+ ) from exc
282
+ delay = self.backoff_base_s * (2**attempt)
283
+ logger.warning("Transient LLM error (%s); retrying in %.1fs", exc, delay)
284
+ attempt += 1
285
+ await asyncio.sleep(delay)
286
+
287
+ @abstractmethod
288
+ async def _complete_raw(
289
+ self,
290
+ messages: list[Message],
291
+ system: str | None,
292
+ max_tokens: int,
293
+ temperature: float | None,
294
+ json_schema: dict[str, Any] | None = None,
295
+ ) -> LLMResponse:
296
+ """Perform one provider call. Raise :class:`TransientLLMError` for retryable failures."""
297
+
298
+
299
+ class LLMSession(LLMClient):
300
+ """A per-run view of a client: same provider and model, separate usage and budget.
301
+
302
+ Provider calls are delegated to the parent client; retries and timeouts use the
303
+ parent's settings.
304
+ """
305
+
306
+ provider: ClassVar[str] = "session"
307
+
308
+ def __init__(self, parent: LLMClient, *, max_cost_usd: float | None = None) -> None:
309
+ super().__init__(
310
+ parent.model,
311
+ max_cost_usd=max_cost_usd,
312
+ timeout_s=parent.timeout_s,
313
+ max_retries=parent.max_retries,
314
+ backoff_base_s=parent.backoff_base_s,
315
+ pricing=parent.pricing,
316
+ )
317
+ self.parent = parent
318
+
319
+ @property
320
+ def client(self) -> LLMClient:
321
+ """The underlying provider client."""
322
+ assert self.parent is not None
323
+ return self.parent
324
+
325
+ async def context_window(self) -> int | None:
326
+ return await self.client.context_window()
327
+
328
+ async def _complete_raw(
329
+ self,
330
+ messages: list[Message],
331
+ system: str | None,
332
+ max_tokens: int,
333
+ temperature: float | None,
334
+ json_schema: dict[str, Any] | None = None,
335
+ ) -> LLMResponse:
336
+ return await self.client._complete_raw(
337
+ messages, system, max_tokens, temperature, json_schema
338
+ )
@@ -0,0 +1,126 @@
1
+ """What a UI needs to set up a model: the providers, the models each one offers right now
2
+ (asked live, so the list never goes stale), and a quick connection check."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ import time
8
+ from dataclasses import dataclass
9
+
10
+ import httpx
11
+
12
+ from margin_core.config import Settings, get_settings
13
+ from margin_core.errors import LLMError
14
+ from margin_core.llm import anthropic, openai
15
+ from margin_core.llm.factory import DEFAULT_MODELS, create_llm, resolve_model
16
+ from margin_core.llm.local import _normalize_base_url
17
+
18
+
19
+ def readable_error(exc: Exception) -> str:
20
+ """The useful part of an LLM error: the server's own message when it sent JSON, plus a
21
+ hint for the common case of a local model that does not fit in memory."""
22
+ text = str(exc).strip()
23
+ match = re.search(r'"message"\s*:\s*"((?:[^"\\]|\\.)*)"', text)
24
+ message = match.group(1) if match else text
25
+ if "requires more system memory" in message:
26
+ message += " (close other programs, or use a smaller model)"
27
+ return message
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Provider:
32
+ id: str
33
+ label: str
34
+ needs_key: bool
35
+ on_device: bool # False: prompts (for the detector, samples of your code) leave the machine
36
+
37
+
38
+ PROVIDERS: tuple[Provider, ...] = (
39
+ Provider("local", "Local server (Ollama, LM Studio, llama.cpp, vLLM)", False, True),
40
+ Provider("anthropic", "Anthropic", True, False),
41
+ Provider("openai", "OpenAI", True, False),
42
+ )
43
+ PROVIDER_IDS = frozenset(p.id for p in PROVIDERS)
44
+
45
+ # OpenAI's list includes embedding, audio and image models; keep the ones that chat
46
+ _OPENAI_NOT_CHAT = ("embedding", "whisper", "tts", "dall-e", "audio", "realtime", "transcribe",
47
+ "image", "moderation", "search", "davinci", "babbage") # fmt: skip
48
+
49
+
50
+ def _key(secret: object) -> str | None:
51
+ value = getattr(secret, "get_secret_value", lambda: None)()
52
+ return value or None
53
+
54
+
55
+ async def list_models(
56
+ provider: str, settings: Settings | None = None, timeout_s: float = 10.0
57
+ ) -> list[str]:
58
+ """Model ids the provider offers, sorted. Raises LLMError with a readable message."""
59
+ settings = settings or get_settings()
60
+ if provider == "local":
61
+ base = _normalize_base_url(settings.local_llm_base_url)
62
+ url, headers = f"{base}/v1/models", {}
63
+ if key := _key(settings.local_llm_api_key):
64
+ headers["Authorization"] = f"Bearer {key}"
65
+ elif provider == "anthropic":
66
+ key = _key(settings.anthropic_api_key)
67
+ if not key:
68
+ raise LLMError("Add an Anthropic API key first.")
69
+ url = f"{anthropic.DEFAULT_BASE_URL}/v1/models?limit=100"
70
+ headers = {"x-api-key": key, "anthropic-version": anthropic.API_VERSION}
71
+ elif provider == "openai":
72
+ key = _key(settings.openai_api_key)
73
+ if not key:
74
+ raise LLMError("Add an OpenAI API key first.")
75
+ url, headers = f"{openai.DEFAULT_BASE_URL}/v1/models", {"Authorization": f"Bearer {key}"}
76
+ else:
77
+ raise LLMError(f"Unknown provider {provider!r}")
78
+
79
+ try:
80
+ async with httpx.AsyncClient(timeout=timeout_s) as client:
81
+ response = await client.get(url, headers=headers)
82
+ except httpx.HTTPError as exc:
83
+ where = settings.local_llm_base_url if provider == "local" else provider
84
+ raise LLMError(f"Can't reach {where}. Is it running, and is the address right?") from exc
85
+ if response.status_code in (401, 403):
86
+ raise LLMError("The API key was rejected.")
87
+ if response.status_code >= 400:
88
+ raise LLMError(f"The server answered {response.status_code} when asked for its models.")
89
+ try:
90
+ ids = [str(m["id"]) for m in response.json().get("data", [])]
91
+ except (ValueError, KeyError, TypeError, AttributeError) as exc:
92
+ raise LLMError("The server's model list was not in the expected format.") from exc
93
+ if provider == "openai":
94
+ ids = [i for i in ids if not any(word in i for word in _OPENAI_NOT_CHAT)]
95
+ elif provider == "local":
96
+ ids = [i for i in ids if "embed" not in i.lower()] # embedding models cannot chat
97
+ return sorted(set(ids))
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class ConnectionCheck:
102
+ ok: bool
103
+ provider: str
104
+ model: str
105
+ latency_ms: int | None
106
+ message: str
107
+
108
+
109
+ async def check_connection(
110
+ provider: str | None = None, model: str | None = None, settings: Settings | None = None
111
+ ) -> ConnectionCheck:
112
+ """Send one tiny prompt and report whether, and how fast, the model answered."""
113
+ settings = settings or get_settings()
114
+ provider = (provider or settings.default_llm_provider).lower()
115
+ model = model or (resolve_model(provider, settings) if provider in DEFAULT_MODELS else "")
116
+ started = time.monotonic()
117
+ try:
118
+ llm = create_llm(provider, model, settings=settings, max_cost_usd=0.05)
119
+ reply = await llm.complete("Reply with the single word OK.", max_tokens=16)
120
+ except LLMError as exc:
121
+ return ConnectionCheck(
122
+ False, provider, model, None, readable_error(exc) or "The call failed."
123
+ )
124
+ latency = int((time.monotonic() - started) * 1000)
125
+ answered = reply.text.strip()[:40] or "(an empty answer)"
126
+ return ConnectionCheck(True, provider, model, latency, f"Answered “{answered}”.")
@@ -0,0 +1,75 @@
1
+ """Build an LLM client from a provider name and settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from margin_core.config import Settings, get_settings
6
+ from margin_core.errors import LLMError
7
+ from margin_core.llm.anthropic import AnthropicLLM
8
+ from margin_core.llm.base import LLMClient
9
+ from margin_core.llm.local import LocalLLM
10
+ from margin_core.llm.mock import MockLLM
11
+ from margin_core.llm.openai import OpenAILLM
12
+
13
+ DEFAULT_MODELS: dict[str, str] = {
14
+ "local": "qwen3.5:9b", # chosen by eval/tools/compare_judges.py (2026-10-19)
15
+ "anthropic": "claude-sonnet-5-5",
16
+ "openai": "gpt-4.1-mini",
17
+ "mock": "mock-model",
18
+ }
19
+
20
+
21
+ PROVIDER_MODEL_SETTING: dict[str, str] = {
22
+ "local": "local_llm_model",
23
+ "anthropic": "anthropic_model",
24
+ "openai": "openai_model",
25
+ }
26
+
27
+
28
+ def resolve_model(provider: str, settings: Settings) -> str:
29
+ """The model to use with ``provider``: its own setting, then ``DEFAULT_LLM_MODEL`` (which
30
+ only applies to the default provider, so it never pairs with another provider), then the
31
+ built-in default."""
32
+ provider = provider.lower()
33
+ field = PROVIDER_MODEL_SETTING.get(provider)
34
+ own = getattr(settings, field) if field else None
35
+ shared = (
36
+ settings.default_llm_model if provider == settings.default_llm_provider.lower() else None
37
+ )
38
+ return own or shared or DEFAULT_MODELS[provider]
39
+
40
+
41
+ def create_llm(
42
+ provider: str | None = None,
43
+ model: str | None = None,
44
+ *,
45
+ max_cost_usd: float | None = None,
46
+ settings: Settings | None = None,
47
+ ) -> LLMClient:
48
+ """Create a client. Missing values fall back to settings, then to ``DEFAULT_MODELS``."""
49
+ settings = settings or get_settings()
50
+ provider = (provider or settings.default_llm_provider).lower()
51
+ if provider not in DEFAULT_MODELS:
52
+ raise LLMError(f"Unknown LLM provider {provider!r}; choose from {sorted(DEFAULT_MODELS)}")
53
+ model = model or resolve_model(provider, settings)
54
+ budget = max_cost_usd if max_cost_usd is not None else settings.max_cost_usd
55
+
56
+ if provider == "local":
57
+ local_key = settings.local_llm_api_key
58
+ return LocalLLM(
59
+ model,
60
+ base_url=settings.local_llm_base_url,
61
+ api_key=local_key.get_secret_value() if local_key else None,
62
+ reasoning_effort=settings.local_llm_reasoning_effort,
63
+ max_cost_usd=budget,
64
+ )
65
+ if provider == "anthropic":
66
+ key = settings.anthropic_api_key
67
+ return AnthropicLLM(
68
+ model, api_key=key.get_secret_value() if key else None, max_cost_usd=budget
69
+ )
70
+ if provider == "openai":
71
+ key = settings.openai_api_key
72
+ return OpenAILLM(
73
+ model, api_key=key.get_secret_value() if key else None, max_cost_usd=budget
74
+ )
75
+ return MockLLM(model=model, max_cost_usd=budget)