Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Add Ollama support #1036

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions guidance/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# local models
from .transformers._transformers import Transformers, TransformersTokenizer
from .llama_cpp import LlamaCpp
from ._ollama import Ollama
from ._mock import Mock, MockChat

# grammarless models (we can't do constrained decoding for them)
Expand Down
49 changes: 49 additions & 0 deletions guidance/models/_ollama.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import os
import json

from pathlib import Path

from ._model import Model
from .llama_cpp._llama_cpp import LlamaCppEngine

base = Path(os.getenv("OLLAMA_MODELS", Path.home() / ".ollama" / "models"))
blobs = base / "blobs"
library = base / "manifests" / "registry.ollama.ai" / "library"


class Ollama(Model):
def __init__(
self,
model: str,
echo=True,
compute_log_probs=False,
chat_template=None,
**llama_cpp_kwargs,
):
"""Wrapper for models pulled using Ollama.

Gets the local model path using the provided model name, and
then instantiates the `LlamaCppEngine` with it and other args.
"""

manifest = library / Path(model.replace(":", "/") if ":" in model else model + "/latest")

if not manifest.exists():
raise ValueError(f"Model '{model}' not found in library.")

with open(manifest, "r") as f:
for layer in json.load(f)["layers"]:
if layer["mediaType"] == "application/vnd.ollama.image.model":
digest: str = layer["digest"]
break
else:
raise ValueError("Model layer not found in manifest.")

engine = LlamaCppEngine(
model=(blobs / digest.replace(":", "-")),
compute_log_probs=compute_log_probs,
chat_template=chat_template,
**llama_cpp_kwargs,
)

super().__init__(engine, echo=echo)
Loading