Jaa


Code interpreter AI agent tools

Important

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.

Built-in Python executor tool

Azure Databricks provides a built-in Python executor tool that lets AI agents run Python code. The Unity Catalog function system.ai.python_exe is available by default and can be used like any other Unity Catalog function-based tool.

Python executor tool

The following example re-creates the built-in tool, system.ai.python_exe 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 that all variables are initialized within the code, and import any necessary standard libraries. The code must print the final result to stdout. Do not attempt to access files or external systems."
    )
    RETURNS STRING
    LANGUAGE PYTHON
    COMMENT "Executes Python code in a stateless sandboxed environment and returns its stdout. The runtime cannot access files or read previous executions' output. All operations must be self-contained, using only standard Python libraries. Calls to other tools are prohibited."
    AS $$
        import sys
        from io import StringIO
        stdout = StringIO()
        stderr = StringIO()
        sys.stdout = stdout
        sys.stderr = stderr
        try:
            exec(code, {})
        except SyntaxError as e: # try escaping characters
            code = code.encode('utf-8').decode('unicode_escape')
            exec(code, {})
        return stdout.getvalue() + stderr.getvalue()
    $$

Next steps

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