Skip to main content
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.

Basic Usage

Define functions in your host code and pass them to run() via the external_functions parameter:

Arguments and Return Values

External functions can accept both positional and keyword arguments:
1

Positional Arguments

2

Keyword Arguments

3

Mixed Arguments

Complex Data Types

External functions can pass and return complex Python types:
All data passed between Monty and external functions is automatically converted between Monty’s internal representation and native Python/JavaScript types.

Multiple External Functions

You can provide multiple external functions in a single execution:

Function Reuse Across Calls

The same function can be called multiple times during execution:

Error Handling

Exceptions raised in external functions propagate to the Monty code:

Catching Exceptions in Monty Code

Exceptions from external functions can be caught using try/except blocks:
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.

Missing Functions

If Monty code calls a function that isn’t provided, a NameError is raised:

Best Practices

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.
  1. Keep functions focused: Each external function should do one thing well
  2. Use type hints: Help type checking catch errors early (see Type Checking)
  3. Handle errors gracefully: Return meaningful error messages that help the agent understand what went wrong
  4. Validate inputs: Don’t trust that the agent will call functions correctly
  5. Use async functions: For I/O-bound operations, use async functions (see Async Execution)

Next Steps

Iterative Execution

Learn how to handle external function calls step-by-step

Async Execution

Use async external functions for better performance