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

Ollama tools #1242

Closed
wants to merge 2 commits into from
Closed
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
7 changes: 6 additions & 1 deletion instructor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,9 @@
if importlib.util.find_spec("writerai") is not None:
from .client_writer import from_writer

__all__ += ["from_writer"]
__all__ += ["from_writer"]

if importlib.util.find_spec("ollama") is not None:
from .client_ollama import from_ollama

__all__ += ["from_ollama"]
76 changes: 76 additions & 0 deletions instructor/client_ollama.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from __future__ import annotations

from typing import Any, overload

import ollama

import instructor


@overload
def from_ollama(
client: (
ollama.Client
),
mode: instructor.Mode = instructor.Mode.OLLAMA_TOOLS,
**kwargs: Any,
) -> instructor.Instructor: ...


@overload
def from_ollama(
client: (
ollama.AsyncClient
),
mode: instructor.Mode = instructor.Mode.OLLAMA_TOOLS,
**kwargs: Any,
) -> instructor.AsyncInstructor: ...


def from_ollama(
client: (
ollama.Client
| ollama.AsyncClient
),
mode: instructor.Mode = instructor.Mode.OLLAMA_TOOLS,
**kwargs: Any,
) -> instructor.Instructor | instructor.AsyncInstructor:
assert (
mode
in {
instructor.Mode.OLLAMA_TOOLS,
}
), "Mode be one of {instructor.Mode.OLLAMA_TOOLS}"

assert isinstance(
client,
(
ollama.Client,
ollama.AsyncClient,
),
), "Client must be an instance of {ollama.Client, ollama.AsyncClient}"

create = client.chat

if isinstance(
client,
(
ollama.Client,
),
):
return instructor.Instructor(
client=client,
create=instructor.patch(create=create, mode=mode),
provider=instructor.Provider.OLLAMA,
mode=mode,
**kwargs,
)

else:
return instructor.AsyncInstructor(
client=client,
create=instructor.patch(create=create, mode=mode),
provider=instructor.Provider.OLLAMA,
mode=mode,
**kwargs,
)
19 changes: 18 additions & 1 deletion instructor/function_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
from functools import wraps
from typing import Annotated, Any, Optional, TypeVar, cast

from docstring_parser import parse
from openai.types.chat import ChatCompletion
from pydantic import (
Expand All @@ -21,7 +22,6 @@
map_to_gemini_function_schema,
)


T = TypeVar("T")

logger = logging.getLogger("instructor")
Expand Down Expand Up @@ -138,6 +138,9 @@ def from_response(

if mode == Mode.WRITER_TOOLS:
return cls.parse_writer_tools(completion, validation_context, strict)

if mode == Mode.OLLAMA_TOOLS:
return cls.parse_ollama_tools(completion, validation_context, strict)

if completion.choices[0].finish_reason == "length":
raise IncompleteOutputException(last_completion=completion)
Expand Down Expand Up @@ -386,6 +389,20 @@ def parse_json(
context=validation_context,
strict=strict,
)

@classmethod
def parse_ollama_tools(
cls: type[BaseModel],
completion: ChatCompletion,
validation_context: Optional[dict[str, Any]] = None,
strict: Optional[bool] = None,
):
message = completion.message.content
return cls.model_validate_json(
message,
context=validation_context,
strict=strict,
)


def openai_schema(cls: type[BaseModel]) -> OpenAISchema:
Expand Down
1 change: 1 addition & 0 deletions instructor/mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Mode(enum.Enum):
FIREWORKS_TOOLS = "fireworks_tools"
FIREWORKS_JSON = "fireworks_json"
WRITER_TOOLS = "writer_tools"
OLLAMA_TOOLS = "ollama_tools"

@classmethod
def warn_mode_functions_deprecation(cls):
Expand Down
7 changes: 7 additions & 0 deletions instructor/process_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,12 @@ def handle_writer_tools(
new_kwargs["tool_choice"] = "auto"
return response_model, new_kwargs

def handle_ollama_tools(
response_model: type[T], new_kwargs: dict[str, Any]
) -> tuple[type[T], dict[str, Any]]:
new_kwargs["format"] = response_model.model_json_schema()
return response_model, new_kwargs


def is_typed_dict(cls) -> bool:
return (
Expand Down Expand Up @@ -715,6 +721,7 @@ def handle_response_model(
Mode.FIREWORKS_JSON: handle_fireworks_json,
Mode.FIREWORKS_TOOLS: handle_fireworks_tools,
Mode.WRITER_TOOLS: handle_writer_tools,
Mode.OLLAMA_TOOLS: handle_ollama_tools,
}

if mode in mode_handlers:
Expand Down
1 change: 1 addition & 0 deletions instructor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class Provider(Enum):
CEREBRAS = "cerebras"
FIREWORKS = "fireworks"
WRITER = "writer"
OLLAMA = "ollama"
UNKNOWN = "unknown"


Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ jsonref = { version = "^1.1.0", optional = true }
cerebras_cloud_sdk = { version = "^1.5.0", optional = true }
fireworks-ai = { version = "^0.15.4", optional = true }
writer-sdk = { version = "^1.2.0", optional = true }
ollama-python = { version = "TODO", optional = true } # Ollama hasn't releaed a version yet

[tool.poetry.extras]
anthropic = ["anthropic", "xmltodict"]
Expand Down
Loading