1
1
from __future__ import annotations
2
2
3
- from types import UnionType
4
3
from typing import Any , Callable , List , Mapping , Optional , Union , get_args , get_origin
5
4
from ollama ._types import Tool
6
5
from collections .abc import Sequence , Set
7
6
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
+
8
20
9
21
# Map both the type and the type reference to the same JSON type
10
22
TYPE_MAP = {
47
59
48
60
def _get_json_type (python_type : Any ) -> str | List [str ]:
49
61
# 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 ):
52
63
args = get_args (python_type )
53
64
# Filter out None/NoneType from union args
54
65
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]:
60
71
return 'null'
61
72
62
73
# Handle generic types (List[int], Dict[str, int], etc.)
63
- if origin is not None :
74
+ if get_origin ( python_type ) is not None :
64
75
# 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 )
66
77
if base_type :
67
78
return base_type
68
79
# 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 )):
71
82
return 'array'
72
- if issubclass (origin , (dict , Mapping )):
83
+ if issubclass (get_origin ( python_type ) , (dict , Mapping )):
73
84
return 'object'
74
85
75
86
# Handle both type objects and type references
@@ -90,8 +101,7 @@ def _get_json_type(python_type: Any) -> str | List[str]:
90
101
91
102
92
103
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 ):
95
105
args = get_args (python_type )
96
106
return any (arg in (None , type (None )) for arg in args )
97
107
return False
0 commit comments