Coverage for src/copytrading_engine/shared/model_providers.py: 100%
22 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""The model services an owner can choose to read posts, and where a custom one may live."""
3from typing import Literal, get_args
4from urllib.parse import urlsplit
6from pydantic import BaseModel, ConfigDict, Field, SecretStr
8type ModelProvider = Literal[
9 "anthropic",
10 "openai",
11 "google",
12 "deepseek",
13 "openrouter",
14 "groq",
15 "xai",
16 "mistral",
17 "together",
18 "fireworks",
19 "cerebras",
20 "moonshotai",
21 "ollama",
22 "openai_compatible",
23]
25MODEL_PROVIDERS: tuple[ModelProvider, ...] = get_args(ModelProvider.__value__)
27# Models that run where the owner chooses: the key is optional and the address is theirs.
28LOCAL_PROVIDERS: frozenset[ModelProvider] = frozenset({"ollama", "openai_compatible"})
30OLLAMA_ENDPOINT = "http://localhost:11434/v1"
32_LOOPBACK = {"localhost", "127.0.0.1", "::1"}
35def endpoint_problem(url: str) -> str | None:
36 """Why an owner-entered model address cannot be used, or None when it can. Plain HTTP is
37 allowed only to this Mac, so a key and the posts never cross the network unencrypted."""
38 parts = urlsplit(url)
39 if parts.scheme not in {"https", "http"} or not parts.hostname:
40 return "The address must start with https:// and name a host"
41 if parts.username or parts.password or parts.query or parts.fragment:
42 return "The address cannot carry a user, password, query, or fragment"
43 if parts.scheme == "http" and parts.hostname not in _LOOPBACK:
44 return "Plain http:// is allowed only for a model on this Mac (localhost)"
45 return None
48class ProviderConfig(BaseModel):
49 """What a reader needs to reach its model. The key is empty only for a model on this Mac or a
50 custom service that takes none; `ProviderConfiguration.reader()` enforces that."""
52 model_config = ConfigDict(frozen=True, hide_input_in_errors=True)
54 api_key: SecretStr
55 model: str = Field(min_length=1)
56 timeout: float = Field(gt=0, allow_inf_nan=False)
57 base_url: str | None = None