llm-pydantic-tools 0.4__tar.gz
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-0.4/LICENSE +21 -0
- llm_pydantic_tools-0.4/PKG-INFO +280 -0
- llm_pydantic_tools-0.4/README.md +257 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools/__init__.py +375 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools/formats.py +189 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools/py.typed +0 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools.egg-info/PKG-INFO +280 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools.egg-info/SOURCES.txt +12 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools.egg-info/dependency_links.txt +1 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools.egg-info/requires.txt +3 -0
- llm_pydantic_tools-0.4/llm_pydantic_tools.egg-info/top_level.txt +1 -0
- llm_pydantic_tools-0.4/pyproject.toml +55 -0
- llm_pydantic_tools-0.4/setup.cfg +4 -0
- llm_pydantic_tools-0.4/tests/test_llm_pydantic_tools.py +732 -0
|
@@ -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,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,257 @@
|
|
|
1
|
+
# LLM Pydantic Tools
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
[](https://github.com/carlosplanchon/llm-pydantic-tools/actions/workflows/ci.yml)
|
|
8
|
+
[](https://pypi.org/project/llm-pydantic-tools/)
|
|
9
|
+
[](https://pypi.org/project/llm-pydantic-tools/)
|
|
10
|
+
[](https://opensource.org/licenses/MIT)
|
|
11
|
+
[](https://deepwiki.com/carlosplanchon/llm-pydantic-tools)
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- **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`.
|
|
16
|
+
- **Lean schemas:** strips the `title` that Pydantic adds to every schema, without touching fields or values that are also called `title`.
|
|
17
|
+
- **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.
|
|
18
|
+
- **`tool_choice` values:** `auto`, `required`, `none`, or forcing this tool, in the format of each API.
|
|
19
|
+
- **Answer validation:** checks the arguments the model returns against the tool's schema.
|
|
20
|
+
- **Typed parsing:** turns the arguments into an instance of your model, running its Pydantic validators.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
uv add llm-pydantic-tools
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or with pip:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install llm-pydantic-tools
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
### Define a tool
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from typing import Literal
|
|
40
|
+
|
|
41
|
+
from pydantic import BaseModel, Field
|
|
42
|
+
|
|
43
|
+
from llm_pydantic_tools import ToolChoiceEnum, ToolSchemaManager, get_tool_choice_dict
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class GetWeather(BaseModel):
|
|
47
|
+
"""Get the current weather in a city."""
|
|
48
|
+
|
|
49
|
+
city: str = Field(description="City name, e.g. Montevideo")
|
|
50
|
+
unit: Literal["celsius", "fahrenheit"] = "celsius"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
weather_tool = ToolSchemaManager(pydantic_obj=GetWeather, tool_name="get_weather")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Without `tool_name`, the tool is named after the model (`GetWeather`).
|
|
57
|
+
|
|
58
|
+
`weather_tool.tools_schema` holds the tool, ready to send:
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
[
|
|
62
|
+
{
|
|
63
|
+
"type": "function",
|
|
64
|
+
"function": {
|
|
65
|
+
"name": "get_weather",
|
|
66
|
+
"description": "Get the current weather in a city.",
|
|
67
|
+
"parameters": {
|
|
68
|
+
"properties": {
|
|
69
|
+
"city": {
|
|
70
|
+
"description": "City name, e.g. Montevideo",
|
|
71
|
+
"type": "string"
|
|
72
|
+
},
|
|
73
|
+
"unit": {
|
|
74
|
+
"default": "celsius",
|
|
75
|
+
"enum": [
|
|
76
|
+
"celsius",
|
|
77
|
+
"fahrenheit"
|
|
78
|
+
],
|
|
79
|
+
"type": "string"
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
"required": [
|
|
83
|
+
"city"
|
|
84
|
+
],
|
|
85
|
+
"type": "object"
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
]
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Call the API
|
|
93
|
+
|
|
94
|
+
Pass `tools_schema` as `tools`, and the result of `get_tool_choice_dict()` as `tool_choice`. With the OpenAI SDK:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from openai import OpenAI
|
|
98
|
+
|
|
99
|
+
client = OpenAI()
|
|
100
|
+
|
|
101
|
+
completion = client.chat.completions.create(
|
|
102
|
+
model="gpt-6-astra",
|
|
103
|
+
messages=[{"role": "user", "content": "What's the weather in Montevideo?"}],
|
|
104
|
+
tools=weather_tool.tools_schema,
|
|
105
|
+
tool_choice=get_tool_choice_dict(ToolChoiceEnum.TOOL_NAME, weather_tool),
|
|
106
|
+
)
|
|
107
|
+
tool_call = completion.choices[0].message.tool_calls[0]
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`ToolChoiceEnum.TOOL_NAME` forces the model to call this tool. `AUTO`, `REQUIRED` and `NONE` map to `"auto"`, `"required"` and `"none"`.
|
|
111
|
+
|
|
112
|
+
### Validate the answer
|
|
113
|
+
|
|
114
|
+
The model does not always follow the schema, so check the arguments before using them. `validate()` raises a `jsonschema.ValidationError` that describes the problem:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
import json
|
|
118
|
+
|
|
119
|
+
from jsonschema import ValidationError
|
|
120
|
+
|
|
121
|
+
arguments = json.loads(tool_call.function.arguments)
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
weather_tool.validate(arguments)
|
|
125
|
+
except ValidationError as error:
|
|
126
|
+
print(error.message) # e.g. 'kelvin' is not one of ['celsius', 'fahrenheit']
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
If you only need a yes or no, `weather_tool.is_valid(arguments)` returns `True` or `False`.
|
|
130
|
+
|
|
131
|
+
`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`.
|
|
132
|
+
|
|
133
|
+
### Get an instance of the model
|
|
134
|
+
|
|
135
|
+
`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:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
weather = weather_tool.parse(tool_call.function.arguments) # a GetWeather
|
|
139
|
+
print(weather.city)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
If the arguments don't fit the model, it raises a `pydantic.ValidationError`.
|
|
143
|
+
|
|
144
|
+
### Start from a JSON schema
|
|
145
|
+
|
|
146
|
+
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`:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
schema_manager = ToolSchemaManager(
|
|
150
|
+
pydantic_obj_json_schema=my_json_schema,
|
|
151
|
+
tool_name="my_tool",
|
|
152
|
+
)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Other formats
|
|
156
|
+
|
|
157
|
+
`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:
|
|
158
|
+
|
|
159
|
+
| `ToolFormat` | API | Pass `get_tool_choice_dict()` as |
|
|
160
|
+
|---|---|---|
|
|
161
|
+
| `CHAT_COMPLETIONS` (default) | OpenAI Chat Completions, and compatible APIs such as Mistral's and Ollama's | `tool_choice` |
|
|
162
|
+
| `RESPONSES` | OpenAI Responses API | `tool_choice` |
|
|
163
|
+
| `ANTHROPIC` | Anthropic's Messages API (Claude) | `tool_choice` |
|
|
164
|
+
| `GEMINI` | Gemini's `generate_content` | `tool_config` |
|
|
165
|
+
| `GEMINI_INTERACTIONS` | Gemini's Interactions API | `generation_config["tool_choice"]` |
|
|
166
|
+
|
|
167
|
+
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.
|
|
168
|
+
|
|
169
|
+
With Anthropic's SDK:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
import anthropic
|
|
173
|
+
|
|
174
|
+
from llm_pydantic_tools import ToolFormat
|
|
175
|
+
|
|
176
|
+
client = anthropic.Anthropic()
|
|
177
|
+
|
|
178
|
+
message = client.messages.create(
|
|
179
|
+
model="claude-opus-5-5",
|
|
180
|
+
max_tokens=16000,
|
|
181
|
+
messages=[{"role": "user", "content": "What's the weather in Montevideo?"}],
|
|
182
|
+
tools=[weather_tool.tool(ToolFormat.ANTHROPIC)],
|
|
183
|
+
tool_choice=get_tool_choice_dict(ToolChoiceEnum.AUTO, weather_tool, ToolFormat.ANTHROPIC),
|
|
184
|
+
)
|
|
185
|
+
for block in message.content:
|
|
186
|
+
if block.type == "tool_use":
|
|
187
|
+
weather_tool.validate(block.input)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
where `weather_tool.tool(ToolFormat.ANTHROPIC)` is:
|
|
191
|
+
|
|
192
|
+
```json
|
|
193
|
+
{
|
|
194
|
+
"name": "get_weather",
|
|
195
|
+
"description": "Get the current weather in a city.",
|
|
196
|
+
"input_schema": {
|
|
197
|
+
"properties": {
|
|
198
|
+
"city": {
|
|
199
|
+
"description": "City name, e.g. Montevideo",
|
|
200
|
+
"type": "string"
|
|
201
|
+
},
|
|
202
|
+
"unit": {
|
|
203
|
+
"default": "celsius",
|
|
204
|
+
"enum": [
|
|
205
|
+
"celsius",
|
|
206
|
+
"fahrenheit"
|
|
207
|
+
],
|
|
208
|
+
"type": "string"
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
"required": [
|
|
212
|
+
"city"
|
|
213
|
+
],
|
|
214
|
+
"type": "object"
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
With Gemini's `generate_content`:
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
from google import genai
|
|
223
|
+
from google.genai import types
|
|
224
|
+
|
|
225
|
+
from llm_pydantic_tools import format_tools
|
|
226
|
+
|
|
227
|
+
client = genai.Client()
|
|
228
|
+
|
|
229
|
+
response = client.models.generate_content(
|
|
230
|
+
model="gemini-flash-latest",
|
|
231
|
+
contents="What's the weather in Montevideo?",
|
|
232
|
+
config=types.GenerateContentConfig(
|
|
233
|
+
tools=format_tools([weather_tool], ToolFormat.GEMINI),
|
|
234
|
+
tool_config=get_tool_choice_dict(ToolChoiceEnum.TOOL_NAME, weather_tool, ToolFormat.GEMINI),
|
|
235
|
+
),
|
|
236
|
+
)
|
|
237
|
+
weather_tool.validate(response.function_calls[0].args)
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## Compatibility
|
|
241
|
+
|
|
242
|
+
The tools are plain dicts, so they work with each provider's SDK or with raw HTTP requests. Keep in mind:
|
|
243
|
+
|
|
244
|
+
- 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.
|
|
245
|
+
- 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.
|
|
246
|
+
- Gemini asks for a description of every function, and supports a subset of JSON Schema.
|
|
247
|
+
- Tool names follow the strictest rule of these APIs (Chat Completions'), so a valid name works with all of them.
|
|
248
|
+
|
|
249
|
+
`llm-pydantic-tools` only depends on Pydantic and jsonschema, which makes it handy when you build the requests yourself or switch between providers.
|
|
250
|
+
|
|
251
|
+
## Contributing
|
|
252
|
+
|
|
253
|
+
Contributions are welcome! Please feel free to submit pull requests, create issues, and suggest improvements to the repository.
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|