You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In addition to per-tool `prepare` methods, you can also define an agent-wide `prepare_tools` function. This function is called at each step of a run and allows you to filter or modify the list of all tool definitions available to the agent for that step. This is especially useful if you want to enable or disable multiple tools at once, or apply global logic based on the current context.
559
+
560
+
The `prepare_tools` function should be of type [`ToolsPrepareFunc`][pydantic_ai.tools.ToolsPrepareFunc], which takes the [`RunContext`][pydantic_ai.tools.RunContext] and a list of [`ToolDefinition`][pydantic_ai.tools.ToolDefinition], and returns a new list of tool definitions (or `None` to disable all tools for that step).
561
+
562
+
!!! note
563
+
The list of tool definitions passed to `prepare_tools` includes both regular tools and tools from any MCP servers attached to the agent.
564
+
565
+
Here's an example that makes all tools strict if the model is an OpenAI model:
return [tool_def for tool_def in tool_defs if tool_def.name !='launch_potato']
623
+
return tool_defs
624
+
625
+
626
+
agent = Agent(
627
+
'test',
628
+
tools=[Tool(launch_potato)],
629
+
prepare_tools=filter_out_tools_by_name,
630
+
deps_type=bool,
631
+
)
632
+
633
+
result = agent.run_sync('testing...', deps=False)
634
+
print(result.output)
635
+
#> {"launch_potato":"Potato launched at a!"}
636
+
result = agent.run_sync('testing...', deps=True)
637
+
print(result.output)
638
+
#> success (no tool calls)
639
+
```
640
+
641
+
_(This example is complete, it can be run "as is")_
642
+
643
+
You can use `prepare_tools` to:
644
+
645
+
- Dynamically enable or disable tools based on the current model, dependencies, or other context
646
+
- Modify tool definitions globally (e.g., set all tools to strict mode, change descriptions, etc.)
647
+
648
+
If both per-tool `prepare` and agent-wide `prepare_tools` are used, the per-tool `prepare` is applied first to each tool, and then `prepare_tools` is called with the resulting list of tool definitions.
0 commit comments