Skip to content
Merged
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
24 changes: 22 additions & 2 deletions packages/genkit-ollama/src/genkit_ollama/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,9 +936,11 @@ def _convert_parameters(input_schema: dict[str, object]) -> ollama_api.Tool.Func
properties_raw = input_schema.get('properties', {})
if isinstance(properties_raw, dict):
properties = cast(dict[str, dict[str, Any]], properties_raw)
for key in properties:
for key, prop in properties.items():
schema.properties[key] = ollama_api.Tool.Function.Parameters.Property(
type=_property_type(properties[key]), description=properties[key].get('description', '')
type=_property_type(prop),
description=prop.get('description', ''),
enum=_property_enum(prop),
)

return schema
Expand Down Expand Up @@ -969,3 +971,21 @@ def _property_type(prop: dict[str, Any]) -> str | list[str] | None:
if types:
return list(dict.fromkeys(types)) # order-preserving dedup
return None


def _property_enum(prop: dict[str, Any]) -> list[Any] | None:
"""Resolves a JSON-schema property's enum choices, including optional Literals.

``Literal['north', 'south'] | None`` serializes as an ``anyOf`` pairing the
enum branch with ``{'type': 'null'}``. Lift the enum only when all other
union branches are ``null`` so non-null unions like ``Literal['a', 'b'] | int``
stay unconstrained.
"""
if 'enum' in prop:
return cast(list[Any] | None, prop['enum'])
union = prop.get('anyOf') or prop.get('oneOf')
if isinstance(union, list) and all(isinstance(entry, dict) for entry in union):
non_null = [entry for entry in union if entry.get('type') != 'null']
if len(non_null) == 1 and isinstance(non_null[0].get('enum'), list):
return cast(list[Any], non_null[0]['enum'])
return None
31 changes: 29 additions & 2 deletions packages/genkit-ollama/tests/config_and_secrets_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@
import json
from collections.abc import Iterator
from dataclasses import dataclass, field
from typing import Any, cast, get_args
from typing import Any, Literal, cast, get_args

import httpx
import ollama as ollama_api
import pytest
from genkit_ollama import Ollama, OllamaConfig
from genkit_ollama._plugin import _ResolvedModel
from pydantic import ValidationError
from pydantic import BaseModel, ValidationError

from genkit import FinishReason, Genkit, GenkitError

Expand Down Expand Up @@ -84,6 +84,33 @@ def make_ai(**plugin_kwargs: Any) -> Genkit:
return Genkit(plugins=[Ollama(**plugin_kwargs)])


@pytest.mark.asyncio
async def test_generate_ollama_preserves_tool_property_enums(server: Server) -> None:
"""Literal choices from a typed tool reach Ollama's chat request."""
ai = make_ai()

class InventoryQuery(BaseModel):
warehouse: Literal['north', 'south']
priority: Literal[0, 1]
region: Literal['us', 'eu'] | None = None
code: Literal['a', 'b'] | int = 0
sku: str

@ai.tool()
async def check_inventory(query: InventoryQuery) -> str:
"""Look up a product in a warehouse."""
return query.sku

await ai.generate(model=MODEL, prompt='Check inventory for SKU-42.', tools=[check_inventory])

properties = server.last_body['tools'][0]['function']['parameters']['properties']
assert properties['warehouse'].get('enum') == ['north', 'south']
assert properties['priority'].get('enum') == [0, 1]
assert properties['region'].get('enum') == ['us', 'eu']
assert 'enum' not in properties['code']
assert 'enum' not in properties['sku']


def test_ollama_config_with_unknown_key_raises_validation_error() -> None:
"""`OllamaConfig(temprature=0.2)` fails naming `temprature`."""
with pytest.raises(ValidationError, match='temprature'):
Expand Down
Loading