llm-pydantic-tools 0.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llm_pydantic_tools/__init__.py +375 -0
- llm_pydantic_tools/formats.py +189 -0
- llm_pydantic_tools/py.typed +0 -0
- llm_pydantic_tools-0.4.dist-info/METADATA +280 -0
- llm_pydantic_tools-0.4.dist-info/RECORD +8 -0
- llm_pydantic_tools-0.4.dist-info/WHEEL +5 -0
- llm_pydantic_tools-0.4.dist-info/licenses/LICENSE +21 -0
- llm_pydantic_tools-0.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
import jsonschema
|
|
6
|
+
from jsonschema.exceptions import ValidationError
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from dataclasses import field
|
|
10
|
+
|
|
11
|
+
import copy
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
from collections.abc import Iterable
|
|
16
|
+
|
|
17
|
+
from typing import Any
|
|
18
|
+
from typing import Generic
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
from typing_extensions import TypeVar
|
|
22
|
+
|
|
23
|
+
from .formats import ToolChoiceEnum
|
|
24
|
+
from .formats import ToolChoiceT
|
|
25
|
+
from .formats import ToolFormat
|
|
26
|
+
from .formats import format_tool
|
|
27
|
+
from .formats import format_tool_choice
|
|
28
|
+
from .formats import group_tools
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"ToolChoiceEnum",
|
|
32
|
+
"ToolChoiceT",
|
|
33
|
+
"ToolFormat",
|
|
34
|
+
"ToolSchemaManager",
|
|
35
|
+
"ToolsSchemaT",
|
|
36
|
+
"format_tools",
|
|
37
|
+
"get_tool_choice_dict",
|
|
38
|
+
"pydantic_obj_to_tool_schema",
|
|
39
|
+
"remove_key_from_dict",
|
|
40
|
+
"remove_keyword_from_schema",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def remove_key_from_dict(
|
|
45
|
+
dict_obj: dict[str, Any],
|
|
46
|
+
key_to_remove: str
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""
|
|
49
|
+
Recursively remove the specified key from a dictionary.
|
|
50
|
+
|
|
51
|
+
:param dict_obj: Dictionary from which the key should be removed
|
|
52
|
+
:param key_to_remove: Key that needs to be removed
|
|
53
|
+
:return: Dictionary without the specified key
|
|
54
|
+
"""
|
|
55
|
+
if isinstance(dict_obj, dict):
|
|
56
|
+
return {
|
|
57
|
+
k: remove_key_from_dict(
|
|
58
|
+
dict_obj=v, key_to_remove=key_to_remove
|
|
59
|
+
) for k, v in dict_obj.items() if k != key_to_remove
|
|
60
|
+
}
|
|
61
|
+
elif isinstance(dict_obj, list):
|
|
62
|
+
return [
|
|
63
|
+
remove_key_from_dict(
|
|
64
|
+
dict_obj=item, key_to_remove=key_to_remove
|
|
65
|
+
) for item in dict_obj
|
|
66
|
+
]
|
|
67
|
+
else:
|
|
68
|
+
return dict_obj
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# JSON Schema keywords whose value is a subschema or a list of subschemas.
|
|
72
|
+
SUBSCHEMA_KEYWORDS: frozenset[str] = frozenset({
|
|
73
|
+
"additionalItems", "additionalProperties", "allOf", "anyOf",
|
|
74
|
+
"contains", "else", "if", "items", "not", "oneOf", "prefixItems",
|
|
75
|
+
"propertyNames", "then", "unevaluatedItems", "unevaluatedProperties"
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
# JSON Schema keywords whose value maps names (field names, model
|
|
79
|
+
# names, patterns...) to subschemas.
|
|
80
|
+
SUBSCHEMA_MAP_KEYWORDS: frozenset[str] = frozenset({
|
|
81
|
+
"$defs", "definitions", "dependentSchemas", "patternProperties",
|
|
82
|
+
"properties"
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def remove_keyword_from_schema(
|
|
87
|
+
schema: Any,
|
|
88
|
+
keyword: str
|
|
89
|
+
) -> Any:
|
|
90
|
+
"""
|
|
91
|
+
Recursively remove the specified keyword from a JSON schema.
|
|
92
|
+
|
|
93
|
+
Unlike remove_key_from_dict, it only walks through subschemas, so
|
|
94
|
+
names (e.g. a field called "title" in "properties") and values
|
|
95
|
+
(e.g. "default", "enum" or "examples") are left untouched.
|
|
96
|
+
|
|
97
|
+
:param schema: JSON schema from which the keyword should be removed
|
|
98
|
+
:param keyword: Keyword that needs to be removed
|
|
99
|
+
:return: JSON schema without the specified keyword
|
|
100
|
+
"""
|
|
101
|
+
if isinstance(schema, list):
|
|
102
|
+
return [
|
|
103
|
+
remove_keyword_from_schema(schema=item, keyword=keyword)
|
|
104
|
+
for item in schema
|
|
105
|
+
]
|
|
106
|
+
if not isinstance(schema, dict):
|
|
107
|
+
return schema
|
|
108
|
+
|
|
109
|
+
clean_schema: dict[str, Any] = {}
|
|
110
|
+
for key, value in schema.items():
|
|
111
|
+
if key == keyword:
|
|
112
|
+
continue
|
|
113
|
+
if key in SUBSCHEMA_KEYWORDS:
|
|
114
|
+
value = remove_keyword_from_schema(schema=value, keyword=keyword)
|
|
115
|
+
elif key in SUBSCHEMA_MAP_KEYWORDS and isinstance(value, dict):
|
|
116
|
+
value = {
|
|
117
|
+
name: remove_keyword_from_schema(
|
|
118
|
+
schema=subschema, keyword=keyword
|
|
119
|
+
) for name, subschema in value.items()
|
|
120
|
+
}
|
|
121
|
+
clean_schema[key] = value
|
|
122
|
+
return clean_schema
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
###########################################
|
|
126
|
+
# #
|
|
127
|
+
# --- PYDANTIC OBJ TO TOOL SCHEMA --- #
|
|
128
|
+
# #
|
|
129
|
+
###########################################
|
|
130
|
+
ToolsSchemaT = list[dict[str, Any]]
|
|
131
|
+
|
|
132
|
+
# Function names accepted by the Chat Completions API.
|
|
133
|
+
TOOL_NAME_PATTERN = re.compile(r"[a-zA-Z0-9_-]{1,64}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def pydantic_obj_to_tool_schema(
|
|
137
|
+
pydantic_obj: type[BaseModel] | None = None,
|
|
138
|
+
pydantic_obj_json_schema: dict[Any, Any] | None = None,
|
|
139
|
+
description: str = "",
|
|
140
|
+
tool_name: str | None = None
|
|
141
|
+
) -> ToolsSchemaT:
|
|
142
|
+
|
|
143
|
+
if pydantic_obj is not None and pydantic_obj_json_schema is not None:
|
|
144
|
+
raise ValueError(
|
|
145
|
+
"Pass either pydantic_obj or pydantic_obj_json_schema, not both"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
if pydantic_obj is not None and not (
|
|
149
|
+
isinstance(pydantic_obj, type) and issubclass(pydantic_obj, BaseModel)
|
|
150
|
+
):
|
|
151
|
+
raise ValueError(
|
|
152
|
+
"pydantic_obj must be a Pydantic model class, "
|
|
153
|
+
f"got {pydantic_obj!r}"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
if pydantic_obj_json_schema is not None and not isinstance(
|
|
157
|
+
pydantic_obj_json_schema, dict
|
|
158
|
+
):
|
|
159
|
+
raise ValueError(
|
|
160
|
+
"pydantic_obj_json_schema must be a dict, "
|
|
161
|
+
f"got {pydantic_obj_json_schema!r}"
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
if not isinstance(description, str):
|
|
165
|
+
raise ValueError(f"description must be a str, got {description!r}")
|
|
166
|
+
|
|
167
|
+
if pydantic_obj is not None:
|
|
168
|
+
json_data = pydantic_obj.model_json_schema()
|
|
169
|
+
elif pydantic_obj_json_schema is not None:
|
|
170
|
+
json_data = pydantic_obj_json_schema
|
|
171
|
+
else:
|
|
172
|
+
raise ValueError(
|
|
173
|
+
"You need to provide either pydantic_obj "
|
|
174
|
+
"or pydantic_obj_json_schema"
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
if tool_name is None:
|
|
178
|
+
if "title" not in json_data:
|
|
179
|
+
raise ValueError(
|
|
180
|
+
"The JSON schema has no title to name the tool after, "
|
|
181
|
+
"pass tool_name"
|
|
182
|
+
)
|
|
183
|
+
tool_name = json_data["title"]
|
|
184
|
+
|
|
185
|
+
if not (
|
|
186
|
+
isinstance(tool_name, str) and TOOL_NAME_PATTERN.fullmatch(tool_name)
|
|
187
|
+
):
|
|
188
|
+
raise ValueError(
|
|
189
|
+
f"Invalid tool name {tool_name!r}: it must have 1 to 64 ASCII "
|
|
190
|
+
"letters, digits, underscores or dashes (pass tool_name to "
|
|
191
|
+
"choose another one)"
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
parameters = remove_keyword_from_schema(
|
|
195
|
+
schema=json_data,
|
|
196
|
+
keyword="title"
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
# The schema description (e.g. the model docstring) is only used when
|
|
200
|
+
# no description is given.
|
|
201
|
+
schema_description = parameters.pop("description", "")
|
|
202
|
+
description = description or schema_description
|
|
203
|
+
|
|
204
|
+
tool_dict = {
|
|
205
|
+
"name": tool_name,
|
|
206
|
+
"description": description,
|
|
207
|
+
"parameters": parameters
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
tools_schema = [
|
|
211
|
+
{
|
|
212
|
+
"type": "function",
|
|
213
|
+
"function": tool_dict
|
|
214
|
+
}
|
|
215
|
+
]
|
|
216
|
+
return tools_schema
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# Model of a manager. Covariant, so that a manager of any model fits where
|
|
220
|
+
# a ToolSchemaManager is expected, and BaseModel by default, for managers
|
|
221
|
+
# built from a JSON schema.
|
|
222
|
+
ModelT = TypeVar("ModelT", bound=BaseModel, covariant=True, default=BaseModel)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class _WeakReferenceable:
|
|
226
|
+
# Gives instances the __weakref__ slot. dataclass(weakref_slot=True)
|
|
227
|
+
# leaves it out on Python 3.12.0 to 3.12.3 when the class also
|
|
228
|
+
# subclasses Generic (CPython gh-118033, fixed in 3.12.4).
|
|
229
|
+
__slots__ = ("__weakref__",)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@dataclass(slots=True)
|
|
233
|
+
class ToolSchemaManager(_WeakReferenceable, Generic[ModelT]):
|
|
234
|
+
pydantic_obj: Optional[type[ModelT]] = None
|
|
235
|
+
pydantic_obj_json_schema: Optional[dict[Any, Any]] = None
|
|
236
|
+
|
|
237
|
+
tools_schema: ToolsSchemaT = field(init=False)
|
|
238
|
+
|
|
239
|
+
description: str = ""
|
|
240
|
+
|
|
241
|
+
# When not given, the tool is named after the schema title.
|
|
242
|
+
tool_name: Optional[str] = None
|
|
243
|
+
|
|
244
|
+
def __post_init__(self) -> None:
|
|
245
|
+
self.tools_schema = pydantic_obj_to_tool_schema(
|
|
246
|
+
pydantic_obj=self.pydantic_obj,
|
|
247
|
+
pydantic_obj_json_schema=self.pydantic_obj_json_schema,
|
|
248
|
+
description=self.description,
|
|
249
|
+
tool_name=self.tool_name
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
self.tool_name = self.tools_schema[0]["function"]["name"]
|
|
253
|
+
|
|
254
|
+
def validate(self, arguments: Any) -> None:
|
|
255
|
+
"""
|
|
256
|
+
Check the arguments of a tool call against the tool schema.
|
|
257
|
+
|
|
258
|
+
:param arguments: Arguments of the tool call, already parsed
|
|
259
|
+
:raises jsonschema.exceptions.ValidationError: If they don't match
|
|
260
|
+
"""
|
|
261
|
+
# The tool parameters exist no matter how the manager was built
|
|
262
|
+
# (from pydantic_obj or from pydantic_obj_json_schema).
|
|
263
|
+
jsonschema.validate(
|
|
264
|
+
instance=arguments,
|
|
265
|
+
schema=self.tools_schema[0]["function"]["parameters"]
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def is_valid(self, arguments: Any) -> bool:
|
|
269
|
+
"""
|
|
270
|
+
Tell whether the arguments of a tool call match the tool schema.
|
|
271
|
+
|
|
272
|
+
:param arguments: Arguments of the tool call, already parsed
|
|
273
|
+
:return: True if they match, False otherwise
|
|
274
|
+
"""
|
|
275
|
+
try:
|
|
276
|
+
self.validate(arguments)
|
|
277
|
+
except ValidationError:
|
|
278
|
+
return False
|
|
279
|
+
return True
|
|
280
|
+
|
|
281
|
+
def parse(self, arguments: Any) -> ModelT:
|
|
282
|
+
"""
|
|
283
|
+
Turn the arguments of a tool call into an instance of the model.
|
|
284
|
+
|
|
285
|
+
Unlike validate(), it runs the Pydantic model, with its validators
|
|
286
|
+
and type conversions.
|
|
287
|
+
|
|
288
|
+
:param arguments: Arguments of the tool call, as a JSON string
|
|
289
|
+
(OpenAI) or already parsed (Anthropic, Gemini)
|
|
290
|
+
:return: Instance of the model
|
|
291
|
+
:raises pydantic.ValidationError: If they don't fit the model
|
|
292
|
+
"""
|
|
293
|
+
if self.pydantic_obj is None:
|
|
294
|
+
raise ValueError(
|
|
295
|
+
"parse() needs a Pydantic model, "
|
|
296
|
+
"build the manager with pydantic_obj"
|
|
297
|
+
)
|
|
298
|
+
if isinstance(arguments, (str, bytes, bytearray)):
|
|
299
|
+
return self.pydantic_obj.model_validate_json(arguments)
|
|
300
|
+
return self.pydantic_obj.model_validate(arguments)
|
|
301
|
+
|
|
302
|
+
def validate_tool_answer(
|
|
303
|
+
self,
|
|
304
|
+
schema_to_validate: Any,
|
|
305
|
+
) -> bool | ValidationError:
|
|
306
|
+
|
|
307
|
+
try:
|
|
308
|
+
self.validate(schema_to_validate)
|
|
309
|
+
# print("JSON data is valid.")
|
|
310
|
+
return True
|
|
311
|
+
except ValidationError as err:
|
|
312
|
+
# print("JSON data is invalid.")
|
|
313
|
+
return err
|
|
314
|
+
|
|
315
|
+
def tool(
|
|
316
|
+
self,
|
|
317
|
+
tool_format: ToolFormat = ToolFormat.CHAT_COMPLETIONS
|
|
318
|
+
) -> dict[str, Any]:
|
|
319
|
+
"""
|
|
320
|
+
Return the tool definition in the format of the given API.
|
|
321
|
+
|
|
322
|
+
:param tool_format: Format of the API that receives the tool
|
|
323
|
+
:return: Tool definition, a copy that can be changed freely
|
|
324
|
+
"""
|
|
325
|
+
function = self.tools_schema[0]["function"]
|
|
326
|
+
return format_tool(
|
|
327
|
+
name=function["name"],
|
|
328
|
+
description=function["description"],
|
|
329
|
+
parameters=copy.deepcopy(function["parameters"]),
|
|
330
|
+
tool_format=tool_format
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def format_tools(
|
|
335
|
+
schema_managers: Iterable[ToolSchemaManager],
|
|
336
|
+
tool_format: ToolFormat = ToolFormat.CHAT_COMPLETIONS
|
|
337
|
+
) -> list[dict[str, Any]]:
|
|
338
|
+
"""
|
|
339
|
+
Build the tools list of a request from several managers.
|
|
340
|
+
|
|
341
|
+
:param schema_managers: Managers of the tools to send
|
|
342
|
+
:param tool_format: Format of the API that receives the tools
|
|
343
|
+
:return: Value for the tools parameter of the API
|
|
344
|
+
"""
|
|
345
|
+
managers = list(schema_managers)
|
|
346
|
+
|
|
347
|
+
# The model calls tools by name, so two tools can't share one.
|
|
348
|
+
names: set[str] = set()
|
|
349
|
+
for manager in managers:
|
|
350
|
+
name = manager.tools_schema[0]["function"]["name"]
|
|
351
|
+
if name in names:
|
|
352
|
+
raise ValueError(f"Duplicate tool name: {name!r}")
|
|
353
|
+
names.add(name)
|
|
354
|
+
|
|
355
|
+
return group_tools(
|
|
356
|
+
tools=[manager.tool(tool_format) for manager in managers],
|
|
357
|
+
tool_format=tool_format
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
#####################################
|
|
362
|
+
# #
|
|
363
|
+
# --- TOOL CHOICE PARAMETER --- #
|
|
364
|
+
# #
|
|
365
|
+
#####################################
|
|
366
|
+
def get_tool_choice_dict(
|
|
367
|
+
tool_choice: ToolChoiceEnum,
|
|
368
|
+
schema_manager: ToolSchemaManager,
|
|
369
|
+
tool_format: ToolFormat = ToolFormat.CHAT_COMPLETIONS
|
|
370
|
+
) -> ToolChoiceT:
|
|
371
|
+
return format_tool_choice(
|
|
372
|
+
tool_choice=tool_choice,
|
|
373
|
+
tool_name=schema_manager.tools_schema[0]["function"]["name"],
|
|
374
|
+
tool_format=tool_format
|
|
375
|
+
)
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
ToolChoiceT = dict[str, Any] | str
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ToolChoiceEnum(StrEnum):
|
|
10
|
+
AUTO = "auto"
|
|
11
|
+
REQUIRED = "required"
|
|
12
|
+
NONE = "none"
|
|
13
|
+
TOOL_NAME = "tool_name"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ToolFormat(StrEnum):
|
|
17
|
+
CHAT_COMPLETIONS = "chat_completions"
|
|
18
|
+
RESPONSES = "responses"
|
|
19
|
+
ANTHROPIC = "anthropic"
|
|
20
|
+
GEMINI = "gemini"
|
|
21
|
+
GEMINI_INTERACTIONS = "gemini_interactions"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def format_tool(
|
|
25
|
+
name: str,
|
|
26
|
+
description: str,
|
|
27
|
+
parameters: dict[str, Any],
|
|
28
|
+
tool_format: ToolFormat
|
|
29
|
+
) -> dict[str, Any]:
|
|
30
|
+
"""
|
|
31
|
+
Build a tool definition in the format of the given API.
|
|
32
|
+
|
|
33
|
+
:param name: Name of the tool
|
|
34
|
+
:param description: Description of the tool
|
|
35
|
+
:param parameters: JSON schema of the tool arguments
|
|
36
|
+
:param tool_format: Format of the API that receives the tool
|
|
37
|
+
:return: Tool definition
|
|
38
|
+
"""
|
|
39
|
+
match tool_format:
|
|
40
|
+
case ToolFormat.CHAT_COMPLETIONS:
|
|
41
|
+
return {
|
|
42
|
+
"type": "function",
|
|
43
|
+
"function": {
|
|
44
|
+
"name": name,
|
|
45
|
+
"description": description,
|
|
46
|
+
"parameters": parameters
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
case ToolFormat.RESPONSES:
|
|
50
|
+
# The OpenAI SDK types require the strict key; None leaves it
|
|
51
|
+
# unset.
|
|
52
|
+
return {
|
|
53
|
+
"type": "function",
|
|
54
|
+
"name": name,
|
|
55
|
+
"description": description,
|
|
56
|
+
"parameters": parameters,
|
|
57
|
+
"strict": None
|
|
58
|
+
}
|
|
59
|
+
case ToolFormat.GEMINI_INTERACTIONS:
|
|
60
|
+
return {
|
|
61
|
+
"type": "function",
|
|
62
|
+
"name": name,
|
|
63
|
+
"description": description,
|
|
64
|
+
"parameters": parameters
|
|
65
|
+
}
|
|
66
|
+
case ToolFormat.ANTHROPIC:
|
|
67
|
+
return {
|
|
68
|
+
"name": name,
|
|
69
|
+
"description": description,
|
|
70
|
+
"input_schema": parameters
|
|
71
|
+
}
|
|
72
|
+
case ToolFormat.GEMINI:
|
|
73
|
+
# A function declaration: Gemini tools group them in
|
|
74
|
+
# {"function_declarations": [...]}.
|
|
75
|
+
return {
|
|
76
|
+
"name": name,
|
|
77
|
+
"description": description,
|
|
78
|
+
"parameters_json_schema": parameters
|
|
79
|
+
}
|
|
80
|
+
case _:
|
|
81
|
+
raise ValueError(f"Invalid tool format: {tool_format}")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def group_tools(
|
|
85
|
+
tools: list[dict[str, Any]],
|
|
86
|
+
tool_format: ToolFormat
|
|
87
|
+
) -> list[dict[str, Any]]:
|
|
88
|
+
"""
|
|
89
|
+
Build the tools list of a request from several tool definitions.
|
|
90
|
+
|
|
91
|
+
Gemini's generate_content groups the function declarations in a
|
|
92
|
+
single tool; the other APIs take the tool definitions as they are.
|
|
93
|
+
|
|
94
|
+
:param tools: Tool definitions in the given format
|
|
95
|
+
:param tool_format: Format of the API that receives the tools
|
|
96
|
+
:return: Value for the tools parameter of the API
|
|
97
|
+
"""
|
|
98
|
+
match tool_format:
|
|
99
|
+
case ToolFormat.GEMINI:
|
|
100
|
+
return [{"function_declarations": tools}] if tools else []
|
|
101
|
+
case (
|
|
102
|
+
ToolFormat.CHAT_COMPLETIONS
|
|
103
|
+
| ToolFormat.RESPONSES
|
|
104
|
+
| ToolFormat.ANTHROPIC
|
|
105
|
+
| ToolFormat.GEMINI_INTERACTIONS
|
|
106
|
+
):
|
|
107
|
+
return tools
|
|
108
|
+
case _:
|
|
109
|
+
raise ValueError(f"Invalid tool format: {tool_format}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def format_tool_choice(
|
|
113
|
+
tool_choice: ToolChoiceEnum,
|
|
114
|
+
tool_name: str,
|
|
115
|
+
tool_format: ToolFormat
|
|
116
|
+
) -> ToolChoiceT:
|
|
117
|
+
"""
|
|
118
|
+
Build the value that tells the API how to choose tools.
|
|
119
|
+
|
|
120
|
+
For Gemini's generate_content it is the tool_config, and for Gemini's
|
|
121
|
+
Interactions API, the tool_choice of the generation_config.
|
|
122
|
+
|
|
123
|
+
:param tool_choice: How the model should choose tools
|
|
124
|
+
:param tool_name: Name of the tool, used by TOOL_NAME
|
|
125
|
+
:param tool_format: Format of the API that receives the value
|
|
126
|
+
:return: Value in the format of the API
|
|
127
|
+
"""
|
|
128
|
+
choices: dict[ToolChoiceEnum, ToolChoiceT]
|
|
129
|
+
match tool_format:
|
|
130
|
+
case ToolFormat.CHAT_COMPLETIONS:
|
|
131
|
+
choices = {
|
|
132
|
+
ToolChoiceEnum.AUTO: "auto",
|
|
133
|
+
ToolChoiceEnum.REQUIRED: "required",
|
|
134
|
+
ToolChoiceEnum.NONE: "none",
|
|
135
|
+
ToolChoiceEnum.TOOL_NAME: {
|
|
136
|
+
"type": "function",
|
|
137
|
+
"function": {"name": tool_name}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
case ToolFormat.RESPONSES:
|
|
141
|
+
choices = {
|
|
142
|
+
ToolChoiceEnum.AUTO: "auto",
|
|
143
|
+
ToolChoiceEnum.REQUIRED: "required",
|
|
144
|
+
ToolChoiceEnum.NONE: "none",
|
|
145
|
+
ToolChoiceEnum.TOOL_NAME: {
|
|
146
|
+
"type": "function",
|
|
147
|
+
"name": tool_name
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
case ToolFormat.ANTHROPIC:
|
|
151
|
+
choices = {
|
|
152
|
+
ToolChoiceEnum.AUTO: {"type": "auto"},
|
|
153
|
+
ToolChoiceEnum.REQUIRED: {"type": "any"},
|
|
154
|
+
ToolChoiceEnum.NONE: {"type": "none"},
|
|
155
|
+
ToolChoiceEnum.TOOL_NAME: {"type": "tool", "name": tool_name}
|
|
156
|
+
}
|
|
157
|
+
case ToolFormat.GEMINI:
|
|
158
|
+
choices = {
|
|
159
|
+
ToolChoiceEnum.AUTO: {
|
|
160
|
+
"function_calling_config": {"mode": "AUTO"}
|
|
161
|
+
},
|
|
162
|
+
ToolChoiceEnum.REQUIRED: {
|
|
163
|
+
"function_calling_config": {"mode": "ANY"}
|
|
164
|
+
},
|
|
165
|
+
ToolChoiceEnum.NONE: {
|
|
166
|
+
"function_calling_config": {"mode": "NONE"}
|
|
167
|
+
},
|
|
168
|
+
ToolChoiceEnum.TOOL_NAME: {
|
|
169
|
+
"function_calling_config": {
|
|
170
|
+
"mode": "ANY",
|
|
171
|
+
"allowed_function_names": [tool_name]
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
case ToolFormat.GEMINI_INTERACTIONS:
|
|
176
|
+
choices = {
|
|
177
|
+
ToolChoiceEnum.AUTO: {"allowed_tools": {"mode": "auto"}},
|
|
178
|
+
ToolChoiceEnum.REQUIRED: {"allowed_tools": {"mode": "any"}},
|
|
179
|
+
ToolChoiceEnum.NONE: {"allowed_tools": {"mode": "none"}},
|
|
180
|
+
ToolChoiceEnum.TOOL_NAME: {
|
|
181
|
+
"allowed_tools": {"mode": "any", "tools": [tool_name]}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
case _:
|
|
185
|
+
raise ValueError(f"Invalid tool format: {tool_format}")
|
|
186
|
+
|
|
187
|
+
if tool_choice not in choices:
|
|
188
|
+
raise ValueError(f"Invalid tool choice: {tool_choice}")
|
|
189
|
+
return choices[tool_choice]
|
|
File without changes
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-pydantic-tools
|
|
3
|
+
Version: 0.4
|
|
4
|
+
Summary: Turn Pydantic models into LLM tools for OpenAI, Anthropic and Gemini.
|
|
5
|
+
Author-email: "Carlos A. Planchón" <carlosandresplanchonprestes@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/carlosplanchon/llm-pydantic-tools.git
|
|
8
|
+
Keywords: llm,ai,gpt,openai,anthropic,claude,gemini,tool,function-calling,schemas,pydantic,json
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: pydantic>=2.7.1
|
|
20
|
+
Requires-Dist: jsonschema>=4.22.0
|
|
21
|
+
Requires-Dist: typing_extensions>=4.12
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# LLM Pydantic Tools
|
|
25
|
+
|
|
26
|
+

|
|
27
|
+
|
|
28
|
+
Turn Pydantic models into function-calling tools. `llm-pydantic-tools` converts a model, or a JSON schema, into the tool format of the main LLM APIs (OpenAI Chat Completions and Responses, Anthropic and Gemini), builds the matching `tool_choice` value, and validates the arguments the model sends back.
|
|
29
|
+
|
|
30
|
+
[](https://github.com/carlosplanchon/llm-pydantic-tools/actions/workflows/ci.yml)
|
|
31
|
+
[](https://pypi.org/project/llm-pydantic-tools/)
|
|
32
|
+
[](https://pypi.org/project/llm-pydantic-tools/)
|
|
33
|
+
[](https://opensource.org/licenses/MIT)
|
|
34
|
+
[](https://deepwiki.com/carlosplanchon/llm-pydantic-tools)
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- **Model to tool:** converts a Pydantic model, or a JSON schema, into a function tool for OpenAI (Chat Completions or Responses), Anthropic or Gemini. The model's docstring becomes the tool description, unless you pass `description`.
|
|
39
|
+
- **Lean schemas:** strips the `title` that Pydantic adds to every schema, without touching fields or values that are also called `title`.
|
|
40
|
+
- **Valid tool names:** names the tool after the model, or after `tool_name`, and checks the name against the API rules: 1 to 64 ASCII letters, digits, underscores or dashes.
|
|
41
|
+
- **`tool_choice` values:** `auto`, `required`, `none`, or forcing this tool, in the format of each API.
|
|
42
|
+
- **Answer validation:** checks the arguments the model returns against the tool's schema.
|
|
43
|
+
- **Typed parsing:** turns the arguments into an instance of your model, running its Pydantic validators.
|
|
44
|
+
|
|
45
|
+
## Installation
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
uv add llm-pydantic-tools
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or with pip:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install llm-pydantic-tools
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Usage
|
|
58
|
+
|
|
59
|
+
### Define a tool
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from typing import Literal
|
|
63
|
+
|
|
64
|
+
from pydantic import BaseModel, Field
|
|
65
|
+
|
|
66
|
+
from llm_pydantic_tools import ToolChoiceEnum, ToolSchemaManager, get_tool_choice_dict
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class GetWeather(BaseModel):
|
|
70
|
+
"""Get the current weather in a city."""
|
|
71
|
+
|
|
72
|
+
city: str = Field(description="City name, e.g. Montevideo")
|
|
73
|
+
unit: Literal["celsius", "fahrenheit"] = "celsius"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
weather_tool = ToolSchemaManager(pydantic_obj=GetWeather, tool_name="get_weather")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Without `tool_name`, the tool is named after the model (`GetWeather`).
|
|
80
|
+
|
|
81
|
+
`weather_tool.tools_schema` holds the tool, ready to send:
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
[
|
|
85
|
+
{
|
|
86
|
+
"type": "function",
|
|
87
|
+
"function": {
|
|
88
|
+
"name": "get_weather",
|
|
89
|
+
"description": "Get the current weather in a city.",
|
|
90
|
+
"parameters": {
|
|
91
|
+
"properties": {
|
|
92
|
+
"city": {
|
|
93
|
+
"description": "City name, e.g. Montevideo",
|
|
94
|
+
"type": "string"
|
|
95
|
+
},
|
|
96
|
+
"unit": {
|
|
97
|
+
"default": "celsius",
|
|
98
|
+
"enum": [
|
|
99
|
+
"celsius",
|
|
100
|
+
"fahrenheit"
|
|
101
|
+
],
|
|
102
|
+
"type": "string"
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
"required": [
|
|
106
|
+
"city"
|
|
107
|
+
],
|
|
108
|
+
"type": "object"
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
]
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Call the API
|
|
116
|
+
|
|
117
|
+
Pass `tools_schema` as `tools`, and the result of `get_tool_choice_dict()` as `tool_choice`. With the OpenAI SDK:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from openai import OpenAI
|
|
121
|
+
|
|
122
|
+
client = OpenAI()
|
|
123
|
+
|
|
124
|
+
completion = client.chat.completions.create(
|
|
125
|
+
model="gpt-6-astra",
|
|
126
|
+
messages=[{"role": "user", "content": "What's the weather in Montevideo?"}],
|
|
127
|
+
tools=weather_tool.tools_schema,
|
|
128
|
+
tool_choice=get_tool_choice_dict(ToolChoiceEnum.TOOL_NAME, weather_tool),
|
|
129
|
+
)
|
|
130
|
+
tool_call = completion.choices[0].message.tool_calls[0]
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`ToolChoiceEnum.TOOL_NAME` forces the model to call this tool. `AUTO`, `REQUIRED` and `NONE` map to `"auto"`, `"required"` and `"none"`.
|
|
134
|
+
|
|
135
|
+
### Validate the answer
|
|
136
|
+
|
|
137
|
+
The model does not always follow the schema, so check the arguments before using them. `validate()` raises a `jsonschema.ValidationError` that describes the problem:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
import json
|
|
141
|
+
|
|
142
|
+
from jsonschema import ValidationError
|
|
143
|
+
|
|
144
|
+
arguments = json.loads(tool_call.function.arguments)
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
weather_tool.validate(arguments)
|
|
148
|
+
except ValidationError as error:
|
|
149
|
+
print(error.message) # e.g. 'kelvin' is not one of ['celsius', 'fahrenheit']
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
If you only need a yes or no, `weather_tool.is_valid(arguments)` returns `True` or `False`.
|
|
153
|
+
|
|
154
|
+
`validate_tool_answer()`, from earlier versions, still returns `True` or the error instead of raising it. Compare its result with `is True`: the error counts as true in an `if`.
|
|
155
|
+
|
|
156
|
+
### Get an instance of the model
|
|
157
|
+
|
|
158
|
+
`validate()` checks the arguments against the JSON schema, so it also works when you start from a schema. If you built the tool from a model, `parse()` goes further: it runs Pydantic, with your validators and type conversions, and returns an instance of the model. It takes the arguments as a JSON string or already parsed:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
weather = weather_tool.parse(tool_call.function.arguments) # a GetWeather
|
|
162
|
+
print(weather.city)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
If the arguments don't fit the model, it raises a `pydantic.ValidationError`.
|
|
166
|
+
|
|
167
|
+
### Start from a JSON schema
|
|
168
|
+
|
|
169
|
+
If you already have the JSON schema, pass it instead of the model. The tool is named after the schema's `title`; if it has none, pass `tool_name`:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
schema_manager = ToolSchemaManager(
|
|
173
|
+
pydantic_obj_json_schema=my_json_schema,
|
|
174
|
+
tool_name="my_tool",
|
|
175
|
+
)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Other formats
|
|
179
|
+
|
|
180
|
+
`tools_schema` holds the tool in the Chat Completions format. `tool()` returns it in the format of another API, and `format_tools()` builds the `tools` list of a request from several managers. `get_tool_choice_dict()` takes the same format as its third argument:
|
|
181
|
+
|
|
182
|
+
| `ToolFormat` | API | Pass `get_tool_choice_dict()` as |
|
|
183
|
+
|---|---|---|
|
|
184
|
+
| `CHAT_COMPLETIONS` (default) | OpenAI Chat Completions, and compatible APIs such as Mistral's and Ollama's | `tool_choice` |
|
|
185
|
+
| `RESPONSES` | OpenAI Responses API | `tool_choice` |
|
|
186
|
+
| `ANTHROPIC` | Anthropic's Messages API (Claude) | `tool_choice` |
|
|
187
|
+
| `GEMINI` | Gemini's `generate_content` | `tool_config` |
|
|
188
|
+
| `GEMINI_INTERACTIONS` | Gemini's Interactions API | `generation_config["tool_choice"]` |
|
|
189
|
+
|
|
190
|
+
The tools always go in `tools`. For Gemini's `generate_content`, `format_tools()` groups them in a single `function_declarations` list, as that API expects, and in every format it rejects two tools with the same name.
|
|
191
|
+
|
|
192
|
+
With Anthropic's SDK:
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
import anthropic
|
|
196
|
+
|
|
197
|
+
from llm_pydantic_tools import ToolFormat
|
|
198
|
+
|
|
199
|
+
client = anthropic.Anthropic()
|
|
200
|
+
|
|
201
|
+
message = client.messages.create(
|
|
202
|
+
model="claude-opus-5-5",
|
|
203
|
+
max_tokens=16000,
|
|
204
|
+
messages=[{"role": "user", "content": "What's the weather in Montevideo?"}],
|
|
205
|
+
tools=[weather_tool.tool(ToolFormat.ANTHROPIC)],
|
|
206
|
+
tool_choice=get_tool_choice_dict(ToolChoiceEnum.AUTO, weather_tool, ToolFormat.ANTHROPIC),
|
|
207
|
+
)
|
|
208
|
+
for block in message.content:
|
|
209
|
+
if block.type == "tool_use":
|
|
210
|
+
weather_tool.validate(block.input)
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
where `weather_tool.tool(ToolFormat.ANTHROPIC)` is:
|
|
214
|
+
|
|
215
|
+
```json
|
|
216
|
+
{
|
|
217
|
+
"name": "get_weather",
|
|
218
|
+
"description": "Get the current weather in a city.",
|
|
219
|
+
"input_schema": {
|
|
220
|
+
"properties": {
|
|
221
|
+
"city": {
|
|
222
|
+
"description": "City name, e.g. Montevideo",
|
|
223
|
+
"type": "string"
|
|
224
|
+
},
|
|
225
|
+
"unit": {
|
|
226
|
+
"default": "celsius",
|
|
227
|
+
"enum": [
|
|
228
|
+
"celsius",
|
|
229
|
+
"fahrenheit"
|
|
230
|
+
],
|
|
231
|
+
"type": "string"
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
"required": [
|
|
235
|
+
"city"
|
|
236
|
+
],
|
|
237
|
+
"type": "object"
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
With Gemini's `generate_content`:
|
|
243
|
+
|
|
244
|
+
```python
|
|
245
|
+
from google import genai
|
|
246
|
+
from google.genai import types
|
|
247
|
+
|
|
248
|
+
from llm_pydantic_tools import format_tools
|
|
249
|
+
|
|
250
|
+
client = genai.Client()
|
|
251
|
+
|
|
252
|
+
response = client.models.generate_content(
|
|
253
|
+
model="gemini-flash-latest",
|
|
254
|
+
contents="What's the weather in Montevideo?",
|
|
255
|
+
config=types.GenerateContentConfig(
|
|
256
|
+
tools=format_tools([weather_tool], ToolFormat.GEMINI),
|
|
257
|
+
tool_config=get_tool_choice_dict(ToolChoiceEnum.TOOL_NAME, weather_tool, ToolFormat.GEMINI),
|
|
258
|
+
),
|
|
259
|
+
)
|
|
260
|
+
weather_tool.validate(response.function_calls[0].args)
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Compatibility
|
|
264
|
+
|
|
265
|
+
The tools are plain dicts, so they work with each provider's SDK or with raw HTTP requests. Keep in mind:
|
|
266
|
+
|
|
267
|
+
- The schemas are not prepared for strict mode (`additionalProperties: false` on every object and every field in `required`). If you use the OpenAI Python SDK and need strict mode, `openai.pydantic_function_tool()` covers that case.
|
|
268
|
+
- The newest Claude models (Opus 5.5, Sonnet 5.5 and Fable 5.1) reject forcing a tool, so `REQUIRED` and `TOOL_NAME` fail there. Use `AUTO` and ask for the tool in the prompt.
|
|
269
|
+
- Gemini asks for a description of every function, and supports a subset of JSON Schema.
|
|
270
|
+
- Tool names follow the strictest rule of these APIs (Chat Completions'), so a valid name works with all of them.
|
|
271
|
+
|
|
272
|
+
`llm-pydantic-tools` only depends on Pydantic and jsonschema, which makes it handy when you build the requests yourself or switch between providers.
|
|
273
|
+
|
|
274
|
+
## Contributing
|
|
275
|
+
|
|
276
|
+
Contributions are welcome! Please feel free to submit pull requests, create issues, and suggest improvements to the repository.
|
|
277
|
+
|
|
278
|
+
## License
|
|
279
|
+
|
|
280
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
llm_pydantic_tools/__init__.py,sha256=nTlVHcHHEMErx0MYV986jwmF8qd257AeVgEU9LZNUmI,11941
|
|
2
|
+
llm_pydantic_tools/formats.py,sha256=vLVjiduL79NOWmo9LzAh5OUQ6Mri6Q3isBWSlZhfnJE,6292
|
|
3
|
+
llm_pydantic_tools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
llm_pydantic_tools-0.4.dist-info/licenses/LICENSE,sha256=Hm7DbQvxEqEzmkD3WbSeAscfgMRaYavzBqkJzd-x81A,1076
|
|
5
|
+
llm_pydantic_tools-0.4.dist-info/METADATA,sha256=VT5RepUocVoHKLV7ZgGWx5Mme8Nl1LINpCQz-IT7CEI,10242
|
|
6
|
+
llm_pydantic_tools-0.4.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
7
|
+
llm_pydantic_tools-0.4.dist-info/top_level.txt,sha256=XY1MaU7QHXUvCpwwFbch3lVIAmmj0_tpcb-DhJxjzMQ,19
|
|
8
|
+
llm_pydantic_tools-0.4.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Carlos A. Planchón
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
llm_pydantic_tools
|