squid-providers 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 @@
1
+ """First-party model transports; import concrete modules explicitly."""
@@ -0,0 +1,86 @@
1
+ """Transport-owned cancellation watcher; Core owns the shared control signal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from collections.abc import Callable
7
+
8
+ from squid_core.providers.base import StreamCancelled
9
+
10
+
11
+ CANCELLATION_POLL_SECONDS = 0.02
12
+ CANCELLATION_MONITOR_JOIN_SECONDS = 0.2
13
+
14
+
15
+ class CancellationMonitor:
16
+ """Close one active transport when a request's cancellation predicate fires.
17
+
18
+ Provider I/O remains on the calling thread. Only this small monitor runs in
19
+ the background, which lets it close a socket/client while the caller is
20
+ blocked waiting for response headers or the next body chunk.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ should_cancel: Callable[[], bool] | None,
26
+ abort: Callable[[], object],
27
+ ) -> None:
28
+ self._should_cancel = should_cancel
29
+ self._abort = abort
30
+ self._stop = threading.Event()
31
+ self._cancelled = threading.Event()
32
+ self._thread: threading.Thread | None = None
33
+
34
+ @property
35
+ def cancelled(self) -> bool:
36
+ return self._cancelled.is_set()
37
+
38
+ def __enter__(self) -> "CancellationMonitor":
39
+ if self._should_cancel is None:
40
+ return self
41
+ if self._should_cancel():
42
+ self._cancelled.set()
43
+ self._abort_safely()
44
+ return self
45
+ self._thread = threading.Thread(
46
+ target=self._watch,
47
+ name="squid-provider-cancellation",
48
+ daemon=True,
49
+ )
50
+ self._thread.start()
51
+ return self
52
+
53
+ def __exit__(self, *_args) -> None:
54
+ self._stop.set()
55
+ if self._thread is not None:
56
+ # The watcher uses Event.wait rather than sleep, so a normal stop
57
+ # wakes it immediately. The bound protects the caller if a foreign
58
+ # transport implements a pathological blocking close method.
59
+ self._thread.join(timeout=CANCELLATION_MONITOR_JOIN_SECONDS)
60
+
61
+ def raise_if_cancelled(self) -> None:
62
+ if self.cancelled or (
63
+ self._should_cancel is not None and self._should_cancel()
64
+ ):
65
+ raise StreamCancelled
66
+
67
+ def _watch(self) -> None:
68
+ while not self._stop.wait(CANCELLATION_POLL_SECONDS):
69
+ try:
70
+ cancelled = bool(self._should_cancel and self._should_cancel())
71
+ except Exception:
72
+ # Cancellation predicates are host control flow. A broken
73
+ # predicate must not replace the active provider request.
74
+ return
75
+ if cancelled:
76
+ self._cancelled.set()
77
+ self._abort_safely()
78
+ return
79
+
80
+ def _abort_safely(self) -> None:
81
+ try:
82
+ self._abort()
83
+ except Exception:
84
+ # The blocked request will surface its own transport error. The
85
+ # cancellation flag remains authoritative at the provider boundary.
86
+ pass
@@ -0,0 +1,278 @@
1
+ """Explicit first-party provider catalog, defaults, configuration and construction.
2
+
3
+ This package owns backend policy. Applications persist sparse overrides and
4
+ choose when to probe services; Core receives a constructed provider only.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import dataclass
11
+ from typing import Any, Mapping
12
+
13
+ from squid_core.providers.base import BaseProvider
14
+ from .ollama import DEFAULT_OLLAMA_BASE_URL, OllamaProvider
15
+ from .openai_compatible import OpenAICompatibleProvider
16
+ from .settings import ProviderSettings
17
+ from .discovery import ModelRecord, discover_model_records
18
+
19
+ CONNECTION_FIELDS = ("base_url", "api_key", "api_key_env")
20
+
21
+ OPENAI_COMPATIBLE_PROVIDERS = frozenset(
22
+ {"lm_studio", "openai_compatible", "openrouter", "squid_models"}
23
+ )
24
+
25
+
26
+ def build_provider(
27
+ settings: ProviderSettings,
28
+ *,
29
+ for_inference: bool = True,
30
+ ) -> BaseProvider:
31
+ """Construct the selected transport for inference or discovery."""
32
+
33
+ # Selection belongs to the application; Core receives only the ready transport.
34
+
35
+ if settings.provider == "ollama":
36
+ return OllamaProvider(
37
+ base_url=settings.base_url or DEFAULT_OLLAMA_BASE_URL,
38
+ temperature=settings.temperature,
39
+ request_timeout=settings.config.get("request_timeout"),
40
+ )
41
+
42
+ if settings.provider in OPENAI_COMPATIBLE_PROVIDERS:
43
+ if settings.base_url is None:
44
+ raise ValueError(f"base_url is required for provider {settings.provider!r}")
45
+ if not settings.api_key and (for_inference or settings.provider != "openrouter"):
46
+ raise ValueError(f"api_key is required for provider {settings.provider!r}")
47
+ return OpenAICompatibleProvider(
48
+ base_url=settings.base_url,
49
+ api_key=settings.api_key,
50
+ temperature=settings.temperature,
51
+ reasoning_mode=settings.reasoning_mode,
52
+ reasoning_token_budget=settings.reasoning_token_budget,
53
+ provider_name=settings.provider,
54
+ )
55
+
56
+ raise ValueError(f"Unsupported built-in provider: {settings.provider}")
57
+
58
+
59
+ def tool_call_content_mode(settings: ProviderSettings) -> str:
60
+ """Return replay content behavior intrinsic to the selected backend."""
61
+
62
+ # OpenRouter requires null content for assistant tool-call replay. Keep
63
+ # backend policy here; ModelAdapter only implements the selected mode.
64
+ return "null" if settings.provider == "openrouter" else "empty"
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class ProviderProfile:
69
+ """Provider-owned defaults and supported configuration for one backend."""
70
+
71
+ provider_id: str
72
+ friendly_name: str
73
+ transport: str
74
+ base_url: str
75
+ api_key: str | None = None
76
+ api_key_env: str | None = None
77
+ config_fields: tuple[str, ...] = ()
78
+ source: str = "Local"
79
+ credential_fields: bool = True
80
+
81
+
82
+ PROVIDER_PROFILES = (
83
+ ProviderProfile(
84
+ "squid_models",
85
+ "Squid Models",
86
+ "OpenAI-compatible chat completions",
87
+ "http://127.0.0.1:8080/v1",
88
+ api_key="local",
89
+ ),
90
+ ProviderProfile(
91
+ "lm_studio",
92
+ "LM Studio",
93
+ "OpenAI-compatible chat completions",
94
+ "http://127.0.0.1:1234/v1",
95
+ api_key="lm-studio",
96
+ ),
97
+ ProviderProfile(
98
+ "ollama",
99
+ "Ollama",
100
+ "native Ollama chat",
101
+ "http://127.0.0.1:11434",
102
+ config_fields=("request_timeout",),
103
+ credential_fields=False,
104
+ ),
105
+ ProviderProfile(
106
+ "openrouter",
107
+ "OpenRouter",
108
+ "OpenAI-compatible chat completions",
109
+ "https://openrouter.ai/api/v1",
110
+ api_key_env="OPENROUTER_API_KEY",
111
+ source="Cloud",
112
+ ),
113
+ ProviderProfile(
114
+ "openai_compatible",
115
+ "OpenAI Compatible",
116
+ "OpenAI-compatible chat completions",
117
+ "http://127.0.0.1:8000/v1",
118
+ api_key="local",
119
+ ),
120
+ )
121
+ PROFILES_BY_ID = {profile.provider_id: profile for profile in PROVIDER_PROFILES}
122
+ VALID_PROVIDERS = frozenset(PROFILES_BY_ID)
123
+
124
+
125
+ def provider_catalog() -> list[dict[str, Any]]:
126
+ """Return fresh, JSON-safe external provider metadata without credentials.
127
+
128
+ Profiles remain the single source of defaults and policy. The existing
129
+ managed transport profile is retained for runtime consumers, but applications
130
+ compose their managed product entry separately from this external catalog.
131
+ Never serialize a resolved config here: it can contain environment secrets.
132
+ """
133
+ return [
134
+ {
135
+ "id": profile.provider_id,
136
+ "label": profile.friendly_name,
137
+ "transport": profile.transport,
138
+ "source": profile.source,
139
+ "connection_fields": list(CONNECTION_FIELDS if profile.credential_fields else ("base_url",)),
140
+ "config_fields": list(profile.config_fields),
141
+ "defaults": {"base_url": profile.base_url, "api_key_env": profile.api_key_env or ""},
142
+ "credentials_required": profile.credential_fields and not bool(profile.api_key),
143
+ }
144
+ for profile in PROVIDER_PROFILES if profile.provider_id != "squid_models"
145
+ ]
146
+
147
+
148
+ def normalize_connection_config(
149
+ provider_id: str,
150
+ values: Mapping[str, Any] | None = None,
151
+ previous: Mapping[str, Any] | None = None,
152
+ ) -> dict[str, Any]:
153
+ """Merge connection edits, retaining saved secrets on empty form submissions.
154
+
155
+ Credential-free transports discard credential fields. Dummy transport keys
156
+ are runtime defaults, never UI metadata. Other supported scoped options are
157
+ preserved so connection edits cannot silently erase backend configuration.
158
+ """
159
+ profile = PROFILES_BY_ID[provider_id]
160
+ result = {"base_url": profile.base_url, "api_key": profile.api_key or "",
161
+ "api_key_env": profile.api_key_env or ""}
162
+ result.update(validate_config(provider_id, previous or {}))
163
+ edits = validate_config(provider_id, values or {})
164
+ for name, value in edits.items():
165
+ if name not in CONNECTION_FIELDS:
166
+ result[name] = value
167
+ if isinstance(edits.get("base_url"), str) and edits["base_url"].strip():
168
+ result["base_url"] = edits["base_url"].strip()
169
+ if edits.get("api_key"):
170
+ result["api_key"] = edits["api_key"]
171
+ result["api_key_env"] = ""
172
+ elif edits.get("api_key_env"):
173
+ result["api_key_env"] = edits["api_key_env"].strip()
174
+ result["api_key"] = ""
175
+ if not profile.credential_fields:
176
+ result["api_key"] = result["api_key_env"] = ""
177
+ elif result.get("api_key"):
178
+ result["api_key_env"] = ""
179
+ return result
180
+
181
+
182
+ def configuration_status(
183
+ provider_id: str, overrides: Mapping[str, Any], *,
184
+ environment: Mapping[str, str] | None = None,
185
+ ) -> dict[str, bool]:
186
+ """Report configuration availability without probing or returning secrets.
187
+
188
+ Configuration is distinct from live readiness; provider_ready owns network
189
+ checks. Missing credential variables are an ordinary unconfigured state.
190
+ """
191
+ profile = PROFILES_BY_ID[provider_id]
192
+ effective = resolve_config(provider_id, overrides, environment=environment,
193
+ require_environment=False)
194
+ available = bool(effective.get("api_key"))
195
+ return {"credentials_configured": available,
196
+ "configured": bool(effective.get("base_url")) and
197
+ (not profile.credential_fields or available)}
198
+
199
+
200
+ def friendly_provider_name(provider_id: str) -> str:
201
+ """Return the stable product label for a provider identity."""
202
+ profile = PROFILES_BY_ID.get(provider_id)
203
+ return profile.friendly_name if profile is not None else provider_id
204
+
205
+
206
+ def resolve_provider_name(value: str) -> str | None:
207
+ """Resolve friendly names and convenient ID spellings case-insensitively."""
208
+ normalized = " ".join(value.strip().lower().replace("-", "_").split())
209
+ for profile in PROVIDER_PROFILES:
210
+ choices = {
211
+ profile.provider_id.lower(),
212
+ profile.provider_id.replace("_", " ").lower(),
213
+ profile.friendly_name.lower(),
214
+ }
215
+ if normalized in choices:
216
+ return profile.provider_id
217
+ return None
218
+
219
+
220
+ def validate_config(provider_id: str, overrides: Mapping[str, Any]) -> dict[str, Any]:
221
+ """Validate supported scoped fields without leaking their names into apps."""
222
+ if provider_id not in PROFILES_BY_ID:
223
+ raise ValueError(f"Unsupported built-in provider: {provider_id}")
224
+ profile = PROFILES_BY_ID[provider_id]
225
+ allowed = set(CONNECTION_FIELDS) | set(profile.config_fields)
226
+ unknown = set(overrides) - allowed
227
+ if unknown:
228
+ raise ValueError(f"providers.{provider_id}: unsupported configuration: {', '.join(sorted(unknown))}")
229
+ for name in CONNECTION_FIELDS:
230
+ value = overrides.get(name)
231
+ if value is not None and not isinstance(value, str):
232
+ raise ValueError(f"providers.{provider_id}.{name} must be a string or null")
233
+ timeout = overrides.get("request_timeout")
234
+ if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (float, int)) or not 0 < timeout < float("inf")):
235
+ raise ValueError(f"providers.{provider_id}.request_timeout must be null or a positive finite number")
236
+ return dict(overrides)
237
+
238
+
239
+ def resolve_config(
240
+ provider_id: str,
241
+ overrides: Mapping[str, Any],
242
+ *,
243
+ environment: Mapping[str, str] | None = None,
244
+ api_key_override: str | None = None,
245
+ require_environment: bool = True,
246
+ ) -> dict[str, Any]:
247
+ """Apply provider defaults and credential variables to sparse saved overrides.
248
+
249
+ Applications pass their product-wide environment overrides as scoped values.
250
+ Provider credential environment names and missing-variable rules live here.
251
+ """
252
+ env = os.environ if environment is None else environment
253
+ profile = PROFILES_BY_ID[provider_id]
254
+ config = validate_config(provider_id, overrides)
255
+ result = {"base_url": profile.base_url, "api_key": profile.api_key, "api_key_env": profile.api_key_env} | config
256
+ variable = result["api_key_env"]
257
+ if api_key_override is not None:
258
+ result["api_key"] = api_key_override
259
+ elif variable is not None:
260
+ secret = env.get(variable)
261
+ if secret is not None:
262
+ result["api_key"] = secret
263
+ elif "api_key_env" in config and require_environment:
264
+ raise ValueError(f"providers.{provider_id}.api_key_env names missing environment variable {variable!r}")
265
+ return result
266
+
267
+
268
+ def provider_ready(settings: ProviderSettings) -> bool:
269
+ """Observe inference readiness without propagating ordinary connection errors."""
270
+ try:
271
+ return build_provider(settings).is_ready()
272
+ except (OSError, RuntimeError, ValueError):
273
+ return False
274
+
275
+
276
+ def discover_models(settings: ProviderSettings) -> list[str]:
277
+ """Return the normalized inventory's ordered IDs without losing exact case."""
278
+ return [record.model_id for record in discover_model_records(settings)]
@@ -0,0 +1,189 @@
1
+ """Provider model inventory requests and normalization, coordinated by catalog.
2
+
3
+ This boundary owns discovery endpoints, parsing and fallbacks, not inference
4
+ readiness or application selection/presentation. Raw transport list_models()
5
+ methods retain their native ordering; public inventories are normalized here.
6
+ """
7
+
8
+ from dataclasses import dataclass, replace
9
+ import json
10
+ import os
11
+ import time
12
+ from urllib import request
13
+ from urllib.error import HTTPError, URLError
14
+
15
+ from .settings import ProviderSettings
16
+ from .ollama import DEFAULT_OLLAMA_BASE_URL
17
+
18
+
19
+ MODEL_DISCOVERY_TIMEOUT_SECONDS = 10
20
+ OPENROUTER_CAPABILITY_TTL_SECONDS = 300
21
+ # Public catalog facts can be shared between UI discovery and a separately
22
+ # constructed inference transport. Scope them to the endpoint, never credentials,
23
+ # and expire them so changing provider metadata does not live forever.
24
+ _openrouter_image_capabilities: dict[str, tuple[float, dict[str, bool]]] = {}
25
+
26
+
27
+ def remember_openrouter_capabilities(base_url: str, models: list[dict]) -> None:
28
+ """Retain authoritative input modalities before inventory drops raw rows."""
29
+ capabilities = {}
30
+ for model in models:
31
+ if not isinstance(model, dict):
32
+ continue
33
+ model_id = model.get("id")
34
+ if not isinstance(model_id, str) or not model_id.strip():
35
+ continue
36
+ architecture = model.get("architecture")
37
+ modalities = architecture.get("input_modalities") if isinstance(architecture, dict) else None
38
+ # Output image support, descriptions and model names are not evidence
39
+ # of image *input*. Unknown or malformed metadata must fail closed.
40
+ capabilities[model_id] = isinstance(modalities, list) and "image" in modalities
41
+ _openrouter_image_capabilities[base_url.rstrip("/")] = (time.monotonic(), capabilities)
42
+
43
+
44
+ def cached_openrouter_capabilities(base_url: str) -> dict[str, bool] | None:
45
+ """Return fresh catalog facts, or None when a catalog request is needed."""
46
+ key = base_url.rstrip("/")
47
+ cached = _openrouter_image_capabilities.get(key)
48
+ if cached is None:
49
+ return None
50
+ observed_at, capabilities = cached
51
+ if time.monotonic() - observed_at >= OPENROUTER_CAPABILITY_TTL_SECONDS:
52
+ _openrouter_image_capabilities.pop(key, None)
53
+ return None
54
+ return capabilities.copy()
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class ModelRecord:
59
+ """Exact provider ID with optional provider-advertised name and load state.
60
+
61
+ None means the provider did not expose that metadata. Labels, selection,
62
+ grouping and other application concepts intentionally do not belong here.
63
+ """
64
+
65
+ model_id: str
66
+ display_name: str | None = None
67
+ loaded: bool | None = None
68
+
69
+
70
+ def _text(value):
71
+ if not isinstance(value, str):
72
+ return None
73
+ return value.strip() or None
74
+
75
+
76
+ def _normalize(records):
77
+ """Deduplicate exact IDs, retaining useful metadata from duplicate rows."""
78
+ unique = {}
79
+ for record in records:
80
+ model_id = record.model_id
81
+ # IDs are opaque provider identifiers. Validate emptiness without
82
+ # rewriting whitespace or case that may matter to a later API call.
83
+ if not isinstance(model_id, str) or not model_id.strip():
84
+ continue
85
+ record = replace(record, model_id=model_id, display_name=_text(record.display_name))
86
+ previous = unique.get(model_id)
87
+ if previous is not None:
88
+ # A duplicate loaded row must not disappear behind an unloaded row.
89
+ record = ModelRecord(
90
+ model_id,
91
+ (record.display_name or previous.display_name)
92
+ if record.loaded and not previous.loaded
93
+ else (previous.display_name or record.display_name),
94
+ True if previous.loaded or record.loaded else (
95
+ False if previous.loaded is False or record.loaded is False else None
96
+ ),
97
+ )
98
+ unique[model_id] = record
99
+ return sorted(unique.values(), key=lambda item: (item.model_id.casefold(), item.model_id))
100
+
101
+
102
+ def _root(base_url):
103
+ root = _text(base_url)
104
+ if root is None:
105
+ raise ValueError("Provider base URL is not configured")
106
+ return root.rstrip("/")
107
+
108
+
109
+ def _native_root(base_url):
110
+ root = _root(base_url)
111
+ return root[:-3].rstrip("/") if root.endswith("/v1") else root
112
+
113
+
114
+ def _get_json(url, api_key=None):
115
+ """Bound discovery requests and keep errors compact and credential-free."""
116
+ headers = {"Accept": "application/json"}
117
+ if api_key:
118
+ headers["Authorization"] = f"Bearer {api_key}"
119
+ try:
120
+ with request.urlopen(request.Request(url, headers=headers),
121
+ timeout=MODEL_DISCOVERY_TIMEOUT_SECONDS) as response:
122
+ payload = response.read()
123
+ except HTTPError as exc:
124
+ raise RuntimeError(f"Model discovery failed with HTTP {exc.code}") from exc
125
+ except URLError as exc:
126
+ raise RuntimeError(f"Model discovery request failed: {exc.reason}") from exc
127
+ except TimeoutError as exc:
128
+ raise RuntimeError("Model discovery timed out") from exc
129
+ try:
130
+ return json.loads(payload.decode("utf-8"))
131
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
132
+ raise RuntimeError("Model discovery returned invalid JSON") from exc
133
+
134
+
135
+ def _rows(payload, field):
136
+ rows = payload.get(field) if isinstance(payload, dict) else None
137
+ if not isinstance(rows, list):
138
+ raise RuntimeError("Model discovery response did not include a model list")
139
+ return [row for row in rows if isinstance(row, dict)]
140
+
141
+
142
+ def discover_model_records(settings: ProviderSettings, *, debug_log=None) -> list[ModelRecord]:
143
+ """Return exact-ID unique inventory ordered by (ID.casefold(), ID).
144
+
145
+ LM Studio and generic compatible services try native LLM metadata first,
146
+ falling back to the compatible catalog when native discovery is unavailable
147
+ or has no usable LLMs. A public OpenRouter catalog needs no inference key.
148
+ """
149
+ provider = settings.provider
150
+ api_key = settings.api_key
151
+ if not api_key and settings.config.get("api_key_env"):
152
+ api_key = os.getenv(settings.config["api_key_env"])
153
+
154
+ def log(message):
155
+ if debug_log is not None:
156
+ debug_log(f"model discovery: provider={provider} {message}")
157
+
158
+ if provider == "ollama":
159
+ url = _native_root(settings.base_url or DEFAULT_OLLAMA_BASE_URL) + "/api/tags"
160
+ log(f"url={url}")
161
+ return _normalize(ModelRecord(row.get("name") or row.get("model"))
162
+ for row in _rows(_get_json(url), "models"))
163
+ if provider not in {"lm_studio", "openai_compatible", "openrouter", "squid_models"}:
164
+ raise ValueError(f"Model discovery is not available for provider: {provider}")
165
+ if provider in {"lm_studio", "openai_compatible"}:
166
+ try:
167
+ url = _native_root(settings.base_url) + "/api/v1/models"
168
+ log(f"native_url={url}")
169
+ records = _normalize(
170
+ ModelRecord(row.get("key"), row.get("display_name"),
171
+ (isinstance(row.get("loaded_instances"), list)
172
+ and bool(row["loaded_instances"]))
173
+ if "loaded_instances" in row else None)
174
+ for row in _rows(_get_json(url, api_key), "models")
175
+ if row.get("type") == "llm"
176
+ )
177
+ if records:
178
+ log(f"loaded_llms={sum(record.loaded is True for record in records)} total_llms={len(records)}")
179
+ return records
180
+ raise RuntimeError("LM Studio native response did not include usable LLM models")
181
+ except (OSError, RuntimeError, ValueError) as exc:
182
+ log(f"native_error={exc.__class__.__name__}: {exc}")
183
+ url = _root(settings.base_url) + "/models"
184
+ log(f"fallback_url={url}")
185
+ models = _rows(_get_json(url, api_key), "data")
186
+ if provider == "openrouter":
187
+ remember_openrouter_capabilities(settings.base_url, models)
188
+ return _normalize(ModelRecord(row.get("id"), row.get("name") or row.get("display_name"))
189
+ for row in models)