ollama2cpp 0.1.1__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.
- ollama2cpp/__init__.py +5 -0
- ollama2cpp/__main__.py +263 -0
- ollama2cpp/commands.py +648 -0
- ollama2cpp/config.py +233 -0
- ollama2cpp/constants.py +42 -0
- ollama2cpp/free_cmd.py +179 -0
- ollama2cpp/gguf.py +357 -0
- ollama2cpp/hardware.py +266 -0
- ollama2cpp/llamacpp.py +247 -0
- ollama2cpp/ollama.py +243 -0
- ollama2cpp/optimize_cmd.py +350 -0
- ollama2cpp/optimizer.py +873 -0
- ollama2cpp/proc.py +130 -0
- ollama2cpp/selector.py +150 -0
- ollama2cpp/server.py +640 -0
- ollama2cpp/ui.py +172 -0
- ollama2cpp/workflow.py +678 -0
- ollama2cpp-0.1.1.dist-info/METADATA +210 -0
- ollama2cpp-0.1.1.dist-info/RECORD +23 -0
- ollama2cpp-0.1.1.dist-info/WHEEL +5 -0
- ollama2cpp-0.1.1.dist-info/entry_points.txt +2 -0
- ollama2cpp-0.1.1.dist-info/licenses/LICENSE +21 -0
- ollama2cpp-0.1.1.dist-info/top_level.txt +1 -0
ollama2cpp/llamacpp.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""llama.cpp binary management and ``llama-server`` argv construction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ollama2cpp import proc, ui
|
|
14
|
+
from ollama2cpp.constants import WINGET_ID
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"LlamaCppError",
|
|
18
|
+
"ServeSettings",
|
|
19
|
+
"build_serve_argv",
|
|
20
|
+
"find_binary",
|
|
21
|
+
"install",
|
|
22
|
+
"update",
|
|
23
|
+
"version",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
RELEASES_URL = "https://github.com/ggml-org/llama.cpp/releases"
|
|
29
|
+
VERSION_TIMEOUT = 15.0
|
|
30
|
+
INSTALL_TIMEOUT = 1800.0
|
|
31
|
+
_BUILD_RE = re.compile(r"\bversion:.*?\(build\s+(\d+)")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class LlamaCppError(RuntimeError):
|
|
35
|
+
"""Raised when llama.cpp cannot be installed or located."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class ServeSettings:
|
|
40
|
+
"""Everything needed to build a ``llama-server`` command line.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
model_path: GGUF file to serve.
|
|
44
|
+
alias: Model name exposed by the API.
|
|
45
|
+
host: Address to listen on.
|
|
46
|
+
port: Port to listen on.
|
|
47
|
+
ctx: Context size in tokens.
|
|
48
|
+
device: Device to offload to (``--device``), or None for llama.cpp's default.
|
|
49
|
+
mmproj: Multimodal projector file, or None.
|
|
50
|
+
profile_args: Extra arguments from the hardware profile.
|
|
51
|
+
extra_args: User-supplied arguments; passed last so they override the profile.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
model_path: Path
|
|
55
|
+
alias: str
|
|
56
|
+
host: str
|
|
57
|
+
port: int
|
|
58
|
+
ctx: int
|
|
59
|
+
device: str | None = None
|
|
60
|
+
mmproj: Path | None = None
|
|
61
|
+
profile_args: list[str] = field(default_factory=list)
|
|
62
|
+
extra_args: list[str] = field(default_factory=list)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _is_windows() -> bool:
|
|
66
|
+
"""Report whether the host is Windows (a seam for tests).
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
bool: True on Windows.
|
|
70
|
+
"""
|
|
71
|
+
return sys.platform == "win32"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _which(name: str) -> Path | None:
|
|
75
|
+
"""Look ``name`` up on PATH, also trying the ``.exe`` suffix on Windows.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
name: Executable name without suffix.
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
Path | None: The resolved executable, or None.
|
|
82
|
+
"""
|
|
83
|
+
candidates = [name, f"{name}.exe"] if _is_windows() else [name]
|
|
84
|
+
for candidate in candidates:
|
|
85
|
+
found = shutil.which(candidate)
|
|
86
|
+
if found:
|
|
87
|
+
return Path(found)
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _winget_glob(name: str) -> Path | None:
|
|
92
|
+
"""Search the WinGet package directory for ``name``.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
name: Executable name without suffix.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
Path | None: The first match (sorted), or None.
|
|
99
|
+
"""
|
|
100
|
+
local = os.environ.get("LOCALAPPDATA")
|
|
101
|
+
if not local:
|
|
102
|
+
return None
|
|
103
|
+
packages = Path(local) / "Microsoft" / "WinGet" / "Packages"
|
|
104
|
+
for candidate in (f"{name}.exe", name):
|
|
105
|
+
matches = sorted(packages.glob(f"{WINGET_ID}_*/{candidate}"))
|
|
106
|
+
if matches:
|
|
107
|
+
return matches[0]
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def find_binary(name: str, configured: str | None = None) -> Path | None:
|
|
112
|
+
"""Locate a llama.cpp executable.
|
|
113
|
+
|
|
114
|
+
Order: the configured path (if it exists), then PATH, then the WinGet package directory.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
name: Executable name without suffix, e.g. ``llama-server``.
|
|
118
|
+
configured: Explicit path from the user's configuration.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
Path | None: The executable, or None when it cannot be found.
|
|
122
|
+
"""
|
|
123
|
+
if configured:
|
|
124
|
+
path = Path(configured)
|
|
125
|
+
if path.is_file():
|
|
126
|
+
return path
|
|
127
|
+
logger.warning("Configured binary %s does not exist; searching elsewhere", configured)
|
|
128
|
+
return _which(name) or _winget_glob(name)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def manual_instructions() -> str:
|
|
132
|
+
"""Build the manual installation hint for this platform.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
str: Human-readable instructions.
|
|
136
|
+
"""
|
|
137
|
+
if _is_windows():
|
|
138
|
+
first = f"winget install --id {WINGET_ID} -e"
|
|
139
|
+
else:
|
|
140
|
+
first = "brew install llama.cpp"
|
|
141
|
+
return f"Install llama.cpp manually with `{first}` or download a build from {RELEASES_URL}"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def install(*, assume_yes: bool = False) -> Path:
|
|
145
|
+
"""Install llama.cpp with winget and return the ``llama-server`` path.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
assume_yes: Skip the confirmation question.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
Path: The installed ``llama-server`` executable.
|
|
152
|
+
|
|
153
|
+
Raises:
|
|
154
|
+
LlamaCppError: Not on Windows, the user declined, winget is missing or failed,
|
|
155
|
+
or the binary still cannot be found afterwards.
|
|
156
|
+
"""
|
|
157
|
+
if not _is_windows():
|
|
158
|
+
msg = f"Automatic installation is only supported on Windows. {manual_instructions()}"
|
|
159
|
+
raise LlamaCppError(msg)
|
|
160
|
+
if not ui.confirm(f"Install llama.cpp with winget ({WINGET_ID})?", assume_yes=assume_yes):
|
|
161
|
+
msg = f"Installation declined. {manual_instructions()}"
|
|
162
|
+
raise LlamaCppError(msg)
|
|
163
|
+
result = proc.run(
|
|
164
|
+
[
|
|
165
|
+
"winget",
|
|
166
|
+
"install",
|
|
167
|
+
"--id",
|
|
168
|
+
WINGET_ID,
|
|
169
|
+
"-e",
|
|
170
|
+
"--accept-package-agreements",
|
|
171
|
+
"--accept-source-agreements",
|
|
172
|
+
],
|
|
173
|
+
timeout=INSTALL_TIMEOUT,
|
|
174
|
+
)
|
|
175
|
+
if result.returncode != 0:
|
|
176
|
+
reason = "winget is not available" if result.returncode == proc.RC_NOT_FOUND else "winget failed"
|
|
177
|
+
msg = f"{reason} (exit code {result.returncode}). {manual_instructions()}"
|
|
178
|
+
raise LlamaCppError(msg)
|
|
179
|
+
found = find_binary("llama-server")
|
|
180
|
+
if found is None:
|
|
181
|
+
msg = f"winget finished but llama-server was not found. {manual_instructions()}"
|
|
182
|
+
raise LlamaCppError(msg)
|
|
183
|
+
return found
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def update() -> proc.ProcResult:
|
|
187
|
+
"""Upgrade llama.cpp with winget.
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
proc.ProcResult: The winget outcome (never raises).
|
|
191
|
+
"""
|
|
192
|
+
return proc.run(["winget", "upgrade", "--id", WINGET_ID, "-e"], timeout=INSTALL_TIMEOUT)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def version(binary: Path) -> str:
|
|
196
|
+
"""Return the compact build string of a llama.cpp binary.
|
|
197
|
+
|
|
198
|
+
``llama-server --version`` prints ``version: 1.0.0-dev (build 12721, commit 79c69f4b0)`` on stderr
|
|
199
|
+
(after any backend-loading lines); the result is ``b12721``.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
binary: Path to a llama.cpp executable.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
str: ``b<build>``, or ``"unknown"`` when it cannot be determined.
|
|
206
|
+
"""
|
|
207
|
+
result = proc.run([str(binary), "--version"], timeout=VERSION_TIMEOUT)
|
|
208
|
+
if result.returncode != 0:
|
|
209
|
+
return "unknown"
|
|
210
|
+
match = _BUILD_RE.search(f"{result.stdout}\n{result.stderr}")
|
|
211
|
+
return f"b{match.group(1)}" if match else "unknown"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def build_serve_argv(binary: Path, s: ServeSettings) -> list[str]:
|
|
215
|
+
"""Build the ``llama-server`` command line.
|
|
216
|
+
|
|
217
|
+
Later arguments override earlier ones in llama-server, so ``extra_args`` come last. Paths are
|
|
218
|
+
single argv elements (never split or quoted).
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
binary: The ``llama-server`` executable.
|
|
222
|
+
s: Serve settings.
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
list[str]: The argv list.
|
|
226
|
+
"""
|
|
227
|
+
argv = [
|
|
228
|
+
str(binary),
|
|
229
|
+
"-m",
|
|
230
|
+
str(s.model_path),
|
|
231
|
+
"--alias",
|
|
232
|
+
s.alias,
|
|
233
|
+
"--host",
|
|
234
|
+
s.host,
|
|
235
|
+
"--port",
|
|
236
|
+
str(s.port),
|
|
237
|
+
"-c",
|
|
238
|
+
str(s.ctx),
|
|
239
|
+
"--jinja",
|
|
240
|
+
]
|
|
241
|
+
if s.device:
|
|
242
|
+
argv += ["--device", s.device]
|
|
243
|
+
if s.mmproj:
|
|
244
|
+
argv += ["--mmproj", str(s.mmproj)]
|
|
245
|
+
argv += s.profile_args
|
|
246
|
+
argv += s.extra_args
|
|
247
|
+
return argv
|
ollama2cpp/ollama.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Read-only access to an Ollama model store (manifests and blobs).
|
|
2
|
+
|
|
3
|
+
Nothing here ever writes to the Ollama directory.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from ollama2cpp.constants import ENV_OLLAMA_MODELS
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
DEFAULT_REGISTRY = "registry.ollama.ai"
|
|
22
|
+
DEFAULT_NAMESPACE = "library"
|
|
23
|
+
DEFAULT_TAG = "latest"
|
|
24
|
+
SYSTEM_MODELS_PATH = Path("/usr/share/ollama/.ollama/models")
|
|
25
|
+
|
|
26
|
+
MEDIA_MODEL = "application/vnd.ollama.image.model"
|
|
27
|
+
MEDIA_PROJECTOR = "application/vnd.ollama.image.projector"
|
|
28
|
+
MEDIA_DRAFT = "application/vnd.ollama.image.draft"
|
|
29
|
+
|
|
30
|
+
_MIN_MANIFEST_DEPTH = 3 # registry / name / tag
|
|
31
|
+
_DIGEST_RE = re.compile(r"[a-z0-9]+:[0-9a-f]+")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ModelNotFoundError(LookupError):
|
|
35
|
+
"""Raised when a requested model is not present in the Ollama store."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _InvalidManifestError(ValueError):
|
|
39
|
+
"""Raised internally when a manifest does not have the expected shape."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Layer:
|
|
44
|
+
"""One layer entry of an Ollama manifest."""
|
|
45
|
+
|
|
46
|
+
media_type: str
|
|
47
|
+
digest: str
|
|
48
|
+
size: int
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class OllamaModel:
|
|
53
|
+
"""An installed Ollama model.
|
|
54
|
+
|
|
55
|
+
``blob_path`` and ``digest`` are ``None`` when the manifest has no model layer.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
name: str
|
|
59
|
+
manifest_path: Path
|
|
60
|
+
layers: tuple[Layer, ...]
|
|
61
|
+
blob_path: Path | None
|
|
62
|
+
digest: str | None
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def size(self) -> int:
|
|
66
|
+
"""Size in bytes of the model layer, ``0`` when there is none."""
|
|
67
|
+
return next((layer.size for layer in self.layers if layer.media_type == MEDIA_MODEL), 0)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def has_projector(self) -> bool:
|
|
71
|
+
"""Whether the model ships a multimodal projector layer."""
|
|
72
|
+
return any(layer.media_type == MEDIA_PROJECTOR for layer in self.layers)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def has_draft(self) -> bool:
|
|
76
|
+
"""Whether the model ships a speculative-decoding draft layer."""
|
|
77
|
+
return any(layer.media_type == MEDIA_DRAFT for layer in self.layers)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def blob_exists(self) -> bool:
|
|
81
|
+
"""Whether the model blob is present on disk (``False`` for dangling manifests)."""
|
|
82
|
+
return self.blob_path is not None and self.blob_path.is_file()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def find_ollama_path(explicit: Path | None = None, env: Mapping[str, str] = os.environ) -> Path | None:
|
|
86
|
+
"""Locate the Ollama models directory.
|
|
87
|
+
|
|
88
|
+
Candidates are tried in order: ``explicit``, ``$OLLAMA_MODELS``, ``~/.ollama/models``,
|
|
89
|
+
``%LOCALAPPDATA%/Ollama/models`` and the Linux system-service path. The first one containing a
|
|
90
|
+
``manifests`` directory wins.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
explicit: A user-provided path, tried first.
|
|
94
|
+
env: Environment mapping to read ``OLLAMA_MODELS`` and ``LOCALAPPDATA`` from.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
Path | None: The models directory, or ``None`` when no candidate qualifies.
|
|
98
|
+
"""
|
|
99
|
+
candidates: list[Path] = []
|
|
100
|
+
if explicit is not None:
|
|
101
|
+
candidates.append(explicit)
|
|
102
|
+
if env.get(ENV_OLLAMA_MODELS):
|
|
103
|
+
candidates.append(Path(env[ENV_OLLAMA_MODELS]))
|
|
104
|
+
candidates.append(Path.home() / ".ollama" / "models")
|
|
105
|
+
if env.get("LOCALAPPDATA"):
|
|
106
|
+
candidates.append(Path(env["LOCALAPPDATA"]) / "Ollama" / "models")
|
|
107
|
+
candidates.append(SYSTEM_MODELS_PATH)
|
|
108
|
+
return next((c for c in candidates if (c / "manifests").is_dir()), None)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def normalize_name(name: str) -> str:
|
|
112
|
+
"""Normalise a user-typed model name to the canonical form used by :func:`list_models`.
|
|
113
|
+
|
|
114
|
+
Lowercases, drops the default ``registry.ollama.ai/`` and ``library/`` prefixes and appends ``:latest``
|
|
115
|
+
when no tag is given.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
name: Model name as typed, e.g. ``Gemma4`` or ``registry.ollama.ai/library/gemma4:12b``.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
str: The canonical name, e.g. ``gemma4:latest``.
|
|
122
|
+
"""
|
|
123
|
+
result = name.strip().lower()
|
|
124
|
+
result = result.removeprefix(f"{DEFAULT_REGISTRY}/").removeprefix(f"{DEFAULT_NAMESPACE}/")
|
|
125
|
+
if ":" not in result.rsplit("/", 1)[-1]:
|
|
126
|
+
result = f"{result}:{DEFAULT_TAG}"
|
|
127
|
+
return result
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _parse_layers(data: object) -> tuple[Layer, ...]:
|
|
131
|
+
"""Validate the manifest JSON and extract its layers.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
data: The decoded manifest JSON.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
tuple[Layer, ...]: The layers, empty when the manifest has none.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
_InvalidManifestError: If the structure is not a valid manifest.
|
|
141
|
+
"""
|
|
142
|
+
if not isinstance(data, dict):
|
|
143
|
+
raise _InvalidManifestError("manifest is not a JSON object")
|
|
144
|
+
raw_layers: Any = data.get("layers", [])
|
|
145
|
+
if not isinstance(raw_layers, list):
|
|
146
|
+
raise _InvalidManifestError("'layers' is not a list")
|
|
147
|
+
layers: list[Layer] = []
|
|
148
|
+
for raw in raw_layers:
|
|
149
|
+
if not isinstance(raw, dict):
|
|
150
|
+
raise _InvalidManifestError("layer is not an object")
|
|
151
|
+
media, digest, size = raw.get("mediaType"), raw.get("digest"), raw.get("size")
|
|
152
|
+
if not isinstance(media, str) or not isinstance(digest, str) or not _DIGEST_RE.fullmatch(digest):
|
|
153
|
+
raise _InvalidManifestError(f"bad layer entry: {raw!r}")
|
|
154
|
+
if not isinstance(size, int) or isinstance(size, bool):
|
|
155
|
+
raise _InvalidManifestError(f"bad layer size: {raw!r}")
|
|
156
|
+
layers.append(Layer(media, digest, size))
|
|
157
|
+
return tuple(layers)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _blob_path(root: Path, digest: str) -> Path:
|
|
161
|
+
"""Map a ``sha256:<hex>`` digest to its ``blobs/sha256-<hex>`` file.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
root: The models directory.
|
|
165
|
+
digest: A validated layer digest.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
Path: Where the blob lives (it may not exist).
|
|
169
|
+
"""
|
|
170
|
+
return root / "blobs" / digest.replace(":", "-")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _read_manifest(root: Path, path: Path) -> OllamaModel:
|
|
174
|
+
"""Build an :class:`OllamaModel` from one manifest file.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
root: The models directory.
|
|
178
|
+
path: The manifest file.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
OllamaModel: The parsed model.
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
_InvalidManifestError: If the path is too shallow or the content is not a valid manifest.
|
|
185
|
+
"""
|
|
186
|
+
parts = path.relative_to(root / "manifests").parts
|
|
187
|
+
if len(parts) < _MIN_MANIFEST_DEPTH:
|
|
188
|
+
raise _InvalidManifestError("manifest path is not registry/name/tag")
|
|
189
|
+
layers = _parse_layers(json.loads(path.read_text(encoding="utf-8")))
|
|
190
|
+
registry, repo, tag = parts[0], "/".join(parts[1:-1]), parts[-1]
|
|
191
|
+
model_layer = next((layer for layer in layers if layer.media_type == MEDIA_MODEL), None)
|
|
192
|
+
return OllamaModel(
|
|
193
|
+
name=normalize_name(f"{registry}/{repo}:{tag}"),
|
|
194
|
+
manifest_path=path,
|
|
195
|
+
layers=layers,
|
|
196
|
+
blob_path=_blob_path(root, model_layer.digest) if model_layer else None,
|
|
197
|
+
digest=model_layer.digest if model_layer else None,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def list_models(root: Path) -> list[OllamaModel]:
|
|
202
|
+
"""List every model whose manifest can be parsed.
|
|
203
|
+
|
|
204
|
+
Unreadable or malformed manifests are logged and skipped.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
root: The models directory (containing ``manifests/`` and ``blobs/``).
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
list[OllamaModel]: Models sorted by name.
|
|
211
|
+
"""
|
|
212
|
+
manifests = root / "manifests"
|
|
213
|
+
if not manifests.is_dir():
|
|
214
|
+
return []
|
|
215
|
+
models: list[OllamaModel] = []
|
|
216
|
+
for path in sorted(p for p in manifests.rglob("*") if p.is_file()):
|
|
217
|
+
try:
|
|
218
|
+
models.append(_read_manifest(root, path))
|
|
219
|
+
except (OSError, ValueError) as exc:
|
|
220
|
+
log.warning("Skipping unreadable manifest %s: %s", path, exc)
|
|
221
|
+
return sorted(models, key=lambda m: m.name)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def resolve_model(root: Path, name: str) -> OllamaModel:
|
|
225
|
+
"""Find an installed model by (loosely typed) name.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
root: The models directory.
|
|
229
|
+
name: Model name as typed; case-insensitive, ``:latest`` implied, default registry optional.
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
OllamaModel: The matching model.
|
|
233
|
+
|
|
234
|
+
Raises:
|
|
235
|
+
ModelNotFoundError: If no model matches; the message lists the available names.
|
|
236
|
+
"""
|
|
237
|
+
wanted = normalize_name(name)
|
|
238
|
+
models = list_models(root)
|
|
239
|
+
for model in models:
|
|
240
|
+
if model.name == wanted:
|
|
241
|
+
return model
|
|
242
|
+
available = ", ".join(m.name for m in models) or "no models installed"
|
|
243
|
+
raise ModelNotFoundError(f"Model {name!r} not found. Available: {available}")
|