Code interpreter AI agent tools

Preview

This feature is in Public Preview.

This article shows how to create code interpreter tools for AI agents using the Mosaic AI Agent Framework. Code interpreters enable agents to execute arbitrary code provided by an interacting user, retrieved from a code base, or written by the agent.

To learn more about agent tools, see Create AI agent tools.

Python executor tool

The following example creates a tool that allows an agent to execute Python code.

Run the following code in a notebook cell. It uses the %sql notebook magic to create a Unity Catalog function called python_exec.

%sql
CREATE OR REPLACE FUNCTION
main.default.python_exec (
code STRING COMMENT 'Python code to execute. Ensure the final result is printed to stdout.'
)
RETURNS STRING
LANGUAGE PYTHON
DETERMINISTIC
COMMENT 'Executes Python code in the sandboxed environment and returns its stdout. The runtime is stateless, meaning outputs from previous tool executions are inaccessible. Variables such as "rows" or "observations" are undefined. Calling other tools within the Python code is NOT permitted. Only standard Python libraries are supported.'
AS $$
import sys
from io import StringIO
sys_stdout = sys.stdout
redirected_output = StringIO()
sys.stdout = redirected_output
exec(code)
sys.stdout = sys_stdout
return redirected_output.getvalue()
$$

Next steps

After you create an agent tool, add the tool to an AI agent. See Add Unity Catalog tools to agents.