Overview
Monty powers code-mode in PydanticAI. Instead of making sequential tool calls, the LLM writes Python code that calls your tools as functions, and Monty executes it safely.Code-mode allows agents to work faster, cheaper, and more reliably by writing Python code instead of relying on traditional tool calling.
How It Works
TheCodeModeToolset wraps your existing FunctionToolset and converts it into executable Python code that Monty can run safely in a sandbox.
Complete Example
Here’s a weather agent that uses Monty’s code-mode to compare weather across multiple cities:1
Define your tools
Create a
FunctionToolset with your agent’s tools:2
Wrap with CodeModeToolset
Replace the
FunctionToolset with a CodeModeToolset wrapper:The
CodeModeToolset converts your function tools into a Python environment that the LLM can write code against.3
Run your agent
Execute the agent normally - it will generate Python code internally:
What CodeModeToolset Does
TheCodeModeToolset wrapper:
- Generates type stubs - Creates Python type definitions for all your tools
- Provides execution context - Gives the LLM access to your tools as callable functions
- Handles external calls - Routes function calls back to your host implementation
- Enforces safety - Runs all code in Monty’s secure sandbox
Benefits Over Traditional Tool Calling
- Faster - Fewer round-trips to the LLM
- Cheaper - Less token usage
- More reliable - Complex logic is easier to express in code
Security
All code runs in Monty’s sandbox with:- No filesystem access
- No network access
- No environment variable access
- Only functions you explicitly provide
Monty ensures that even malicious code generated by the LLM cannot escape the sandbox or access your host system.
