Learn how to define and use external functions in Monty to connect your Python code with host environment capabilities
External functions allow your Monty code to call functions defined in the host environment. This is essential for giving your agent code access to tools, APIs, and other capabilities while maintaining security.
Define functions in your host code and pass them to run() via the external_functions parameter:
import pydantic_monty# Code that calls an external functionm = pydantic_monty.Monty('double(x)', inputs=['x'])# Provide the external function implementation at runtimeresult = m.run( inputs={'x': 5}, external_functions={'double': lambda x: x * 2})print(result) # 10
All data passed between Monty and external functions is automatically converted between Monty’s internal representation and native Python/JavaScript types.
Exception types are preserved across the boundary, including exception hierarchies. For example, a ZeroDivisionError raised by an external function can be caught by an ArithmeticError handler in Monty code.
If Monty code calls a function that isn’t provided, a NameError is raised:
m = pydantic_monty.Monty('missing()')try: m.run() # No external_functions providedexcept pydantic_monty.MontyRuntimeError as e: inner = e.exception() print(type(inner)) # <class 'NameError'> print(str(inner)) # "name 'missing' is not defined"
Only provide external functions that are safe for your agent to call. External functions run in your host environment with full access to system resources.
Keep functions focused: Each external function should do one thing well
Use type hints: Help type checking catch errors early (see Type Checking)
Handle errors gracefully: Return meaningful error messages that help the agent understand what went wrong
Validate inputs: Don’t trust that the agent will call functions correctly
Use async functions: For I/O-bound operations, use async functions (see Async Execution)