Skip to content

Commit 4fcdf70

Browse files
committed
Trying stuff out
1 parent 97aa167 commit 4fcdf70

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

ollama/_utils.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11
from __future__ import annotations
22

3-
from types import UnionType
43
from typing import Any, Callable, List, Mapping, Optional, Union, get_args, get_origin
54
from ollama._types import Tool
65
from collections.abc import Sequence, Set
76
from typing import Dict, Set as TypeSet
7+
import sys
8+
9+
# Type compatibility layer
10+
if sys.version_info >= (3, 10):
11+
from types import UnionType
12+
13+
def is_union(tp: Any) -> bool:
14+
return get_origin(tp) in (Union, UnionType)
15+
else:
16+
17+
def is_union(tp: Any) -> bool:
18+
return get_origin(tp) is Union
19+
820

921
# Map both the type and the type reference to the same JSON type
1022
TYPE_MAP = {
@@ -47,8 +59,7 @@
4759

4860
def _get_json_type(python_type: Any) -> str | List[str]:
4961
# Handle Optional types (Union[type, None] and type | None)
50-
origin = get_origin(python_type)
51-
if origin is UnionType or origin is Union:
62+
if is_union(python_type):
5263
args = get_args(python_type)
5364
# Filter out None/NoneType from union args
5465
non_none_args = [arg for arg in args if arg not in (None, type(None))]
@@ -60,16 +71,16 @@ def _get_json_type(python_type: Any) -> str | List[str]:
6071
return 'null'
6172

6273
# Handle generic types (List[int], Dict[str, int], etc.)
63-
if origin is not None:
74+
if get_origin(python_type) is not None:
6475
# Get the base type (List, Dict, etc.)
65-
base_type = TYPE_MAP.get(origin, None)
76+
base_type = TYPE_MAP.get(get_origin(python_type), None)
6677
if base_type:
6778
return base_type
6879
# If it's a subclass of known abstract base classes, map to appropriate type
69-
if isinstance(origin, type):
70-
if issubclass(origin, (list, Sequence, tuple, set, Set)):
80+
if isinstance(get_origin(python_type), type):
81+
if issubclass(get_origin(python_type), (list, Sequence, tuple, set, Set)):
7182
return 'array'
72-
if issubclass(origin, (dict, Mapping)):
83+
if issubclass(get_origin(python_type), (dict, Mapping)):
7384
return 'object'
7485

7586
# Handle both type objects and type references
@@ -90,8 +101,7 @@ def _get_json_type(python_type: Any) -> str | List[str]:
90101

91102

92103
def _is_optional_type(python_type: Any) -> bool:
93-
origin = get_origin(python_type)
94-
if origin is UnionType or origin is Union:
104+
if is_union(python_type):
95105
args = get_args(python_type)
96106
return any(arg in (None, type(None)) for arg in args)
97107
return False

0 commit comments

Comments
 (0)