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 ADDED
@@ -0,0 +1,5 @@
1
+ """ollama2cpp: start llama-server (llama.cpp) on the GGUF blobs of your Ollama models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.1"
ollama2cpp/__main__.py ADDED
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env python3
2
+ """ollama2cpp command line interface.
3
+
4
+ Console app to start llama-server (llama.cpp) from Ollama available models.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import sys
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Annotated
15
+
16
+ import typer
17
+
18
+ from ollama2cpp import __version__, commands, free_cmd, optimize_cmd, ui, workflow
19
+ from ollama2cpp.constants import ENV_OLLAMA_MODEL, EXIT_INTERRUPTED
20
+ from ollama2cpp.llamacpp import LlamaCppError
21
+ from ollama2cpp.ollama import ModelNotFoundError
22
+
23
+ logger = logging.getLogger(__name__)
24
+ __all__ = ["app", "main"]
25
+
26
+
27
+ @dataclass
28
+ class _State:
29
+ """Global options populated by the app callback before each command."""
30
+
31
+ verbose: bool = False
32
+ model: str | None = None
33
+ model_explicit: str | None = None # the model from a `--model` flag, not from the environment
34
+ model_from_env: bool = False # `model` came from $OLLAMA_MODEL
35
+
36
+
37
+ _state = _State()
38
+
39
+ app = typer.Typer(
40
+ name="ollama2cpp",
41
+ help="Start llama-server (llama.cpp) on the GGUF blobs of your Ollama models.",
42
+ epilog=f"Set [bold]{ENV_OLLAMA_MODEL}[/bold] to choose the default model.",
43
+ invoke_without_command=True,
44
+ add_completion=False,
45
+ rich_markup_mode="rich",
46
+ pretty_exceptions_show_locals=False,
47
+ )
48
+
49
+
50
+ @app.callback()
51
+ def _configure(
52
+ ctx: typer.Context,
53
+ verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Verbose logging.")] = False,
54
+ model: Annotated[
55
+ str | None,
56
+ typer.Option("--model", "-m", help="Ollama model name (default: auto-select).", envvar=ENV_OLLAMA_MODEL),
57
+ ] = None,
58
+ version: Annotated[bool, typer.Option("--version", help="Show the version and exit.")] = False,
59
+ ) -> None:
60
+ """Record the global options; show help when no command is given."""
61
+ if version:
62
+ ui.show_notice("info", f"ollama2cpp {__version__}")
63
+ raise typer.Exit(code=0)
64
+ _state.verbose = verbose
65
+ _state.model = model
66
+ source = ctx.get_parameter_source("model")
67
+ _state.model_from_env = model is not None and source is not None and source.name == "ENVIRONMENT"
68
+ _state.model_explicit = None if _state.model_from_env else model
69
+ logging.basicConfig(
70
+ level=logging.INFO if verbose else logging.WARNING,
71
+ format="%(levelname)s %(name)s: %(message)s",
72
+ )
73
+ if ctx.invoked_subcommand is None:
74
+ _finish(lambda: workflow.run_serve(workflow.ServeOptions(model=model, model_from_env=_state.model_from_env)))
75
+
76
+
77
+ def _finish(action: Callable[[], int]) -> None:
78
+ """Run ``action`` and exit with its code; failures become one error line (traceback only with ``--verbose``).
79
+
80
+ Args:
81
+ action: The command body, returning the exit code.
82
+
83
+ Raises:
84
+ Exit: Always, carrying the exit code.
85
+ """
86
+ try:
87
+ code = action()
88
+ except (workflow.WorkflowError, LlamaCppError, ModelNotFoundError) as exc:
89
+ ui.show_notice("error", str(exc))
90
+ code = 1
91
+ except KeyboardInterrupt:
92
+ ui.show_notice("warn", "Interrupted.")
93
+ code = EXIT_INTERRUPTED
94
+ except Exception as exc:
95
+ logger.debug("Unexpected failure", exc_info=True)
96
+ ui.show_notice("error", f"Unexpected error: {exc}")
97
+ if _state.verbose:
98
+ ui.console.print_exception(show_locals=False)
99
+ code = 1
100
+ raise typer.Exit(code=code)
101
+
102
+
103
+ @app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
104
+ def serve(
105
+ ctx: typer.Context,
106
+ model: Annotated[str | None, typer.Option("--model", "-m", help="Ollama model name (default: saved/auto).")] = None,
107
+ ollama_path: Annotated[
108
+ Path | None, typer.Option("--ollama-path", help="Ollama models directory (contains manifests/ and blobs/).")
109
+ ] = None,
110
+ host: Annotated[
111
+ str | None, typer.Option("--host", help="Address to listen on (default: config or 127.0.0.1).")
112
+ ] = None,
113
+ port: Annotated[
114
+ int | None, typer.Option("--port", min=1, max=65535, help="Port to listen on (default 8080).")
115
+ ] = None,
116
+ context: Annotated[int | None, typer.Option("--ctx", min=1, help="Context size in tokens (default 8192).")] = None,
117
+ detach: Annotated[bool, typer.Option("--detach", help="Run in the background; return once ready.")] = False,
118
+ restart: Annotated[bool, typer.Option("--restart", help="Replace our own running server.")] = False,
119
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Print the command and exit.")] = False,
120
+ vision: Annotated[
121
+ bool, typer.Option("--vision", help="Load the multimodal projector when the model has one.")
122
+ ] = False,
123
+ yes: Annotated[
124
+ bool, typer.Option("--yes", "-y", help="Answer yes to questions (e.g. installing llama.cpp).")
125
+ ] = False,
126
+ ) -> None:
127
+ """Start llama-server on an Ollama model. Extra llama-server arguments go after `--`."""
128
+ opts = workflow.ServeOptions(
129
+ model=model or _state.model,
130
+ model_from_env=not model and _state.model_from_env,
131
+ ollama_path=ollama_path,
132
+ host=host,
133
+ port=port,
134
+ ctx=context,
135
+ detach=detach,
136
+ restart=restart,
137
+ dry_run=dry_run,
138
+ vision=vision,
139
+ assume_yes=yes,
140
+ extra_args=tuple(ctx.args),
141
+ )
142
+ _finish(lambda: workflow.run_serve(opts))
143
+
144
+
145
+ @app.command("list")
146
+ def list_cmd(
147
+ as_json: Annotated[bool, typer.Option("--json", help="Print a JSON array instead of a table.")] = False,
148
+ ) -> None:
149
+ """List the installed Ollama models (kind, size, quantisation, fit, optimization state)."""
150
+ _finish(lambda: commands.run_list(as_json=as_json))
151
+
152
+
153
+ @app.command()
154
+ def info(model: Annotated[str, typer.Argument(help="Ollama model name.")]) -> None:
155
+ """Show the GGUF details, layers, VRAM need and saved profiles of a model."""
156
+ _finish(lambda: commands.run_info(model))
157
+
158
+
159
+ @app.command()
160
+ def status() -> None:
161
+ """Show the server state, configuration, GPU memory and the default model's profile."""
162
+ _finish(commands.run_status)
163
+
164
+
165
+ @app.command()
166
+ def stop() -> None:
167
+ """Stop the server started by ollama2cpp (never touches other processes)."""
168
+ _finish(commands.run_stop)
169
+
170
+
171
+ @app.command()
172
+ def free(
173
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Do not ask before stopping Ollama.")] = False,
174
+ ) -> None:
175
+ """Stop Ollama and our llama-server and free the VRAM they hold (other processes are left alone)."""
176
+ _finish(lambda: free_cmd.run_free(assume_yes=yes))
177
+
178
+
179
+ @app.command()
180
+ def doctor() -> None:
181
+ """Check llama.cpp, Ollama, the GPU and the configuration, with fix hints."""
182
+ _finish(commands.run_doctor)
183
+
184
+
185
+ @app.command()
186
+ def update() -> None:
187
+ """Upgrade llama.cpp with winget."""
188
+ _finish(commands.run_update)
189
+
190
+
191
+ @app.command("config")
192
+ def config_cmd(
193
+ set_values: Annotated[
194
+ list[str] | None,
195
+ typer.Option(
196
+ "--set", metavar="KEY=VALUE", help=f"Set a key ({', '.join(commands.SETTABLE_KEYS)}); repeatable."
197
+ ),
198
+ ] = None,
199
+ reset: Annotated[bool, typer.Option("--reset", help="Delete the configuration file.")] = False,
200
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Do not ask before --reset.")] = False,
201
+ ) -> None:
202
+ """Show the configuration and its path; change settings with --set, or delete it with --reset."""
203
+ _finish(lambda: commands.run_config(set_values=set_values or [], reset=reset, assume_yes=yes))
204
+
205
+
206
+ @app.command()
207
+ def optimize(
208
+ model: Annotated[str | None, typer.Argument(help="Ollama model name (default: saved/auto).")] = None,
209
+ quick: Annotated[bool, typer.Option("--quick", help="Save the heuristic settings without benchmarking.")] = False,
210
+ all_models: Annotated[bool, typer.Option("--all", help="Optimize every chat model.")] = False,
211
+ time_limit: Annotated[
212
+ float, typer.Option("--time-limit", min=0, help="Benchmark budget per model, in seconds.")
213
+ ] = optimize_cmd.DEFAULT_TIME_LIMIT,
214
+ context: Annotated[
215
+ int | None, typer.Option("--ctx", min=1, help="Context size to optimize for (default 8192).")
216
+ ] = None,
217
+ allow_kv_quant: Annotated[
218
+ bool, typer.Option("--allow-kv-quant", help="Also try a q8_0 KV cache (may affect quality).")
219
+ ] = False,
220
+ unload_ollama: Annotated[
221
+ bool, typer.Option("--unload-ollama", help="Ask Ollama to unload its models if they hold the VRAM.")
222
+ ] = False,
223
+ stop_server: Annotated[
224
+ bool, typer.Option("--stop-server", help="Stop our running server first (it holds VRAM).")
225
+ ] = False,
226
+ yes: Annotated[
227
+ bool, typer.Option("--yes", "-y", help="Answer yes to questions (e.g. installing llama.cpp).")
228
+ ] = False,
229
+ ) -> None:
230
+ """Find the fastest llama-server settings for a model on this machine and save them."""
231
+ opts = optimize_cmd.OptimizeOptions(
232
+ # `--all` ignores a model that only came from $OLLAMA_MODEL; an explicit MODEL or `--model` still conflicts
233
+ model=model or (_state.model_explicit if all_models else _state.model),
234
+ model_from_env=not model and not all_models and _state.model_from_env,
235
+ quick=quick,
236
+ all_models=all_models,
237
+ time_limit=time_limit,
238
+ ctx=context,
239
+ allow_kv_quant=allow_kv_quant,
240
+ unload_ollama=unload_ollama,
241
+ stop_server=stop_server,
242
+ assume_yes=yes,
243
+ )
244
+ _finish(lambda: optimize_cmd.run_optimize(opts))
245
+
246
+
247
+ @app.command("ver")
248
+ def version_cmd() -> None:
249
+ """Print the version."""
250
+ ui.show_notice("info", f"ollama2cpp {__version__}")
251
+
252
+
253
+ def main() -> None:
254
+ """CLI entry point registered in pyproject.toml."""
255
+ for stream in (sys.stdout, sys.stderr):
256
+ reconfigure = getattr(stream, "reconfigure", None)
257
+ if reconfigure is not None:
258
+ reconfigure(encoding="utf-8", errors="replace")
259
+ app()
260
+
261
+
262
+ if __name__ == "__main__":
263
+ main()