Execute Python Code Securely on Azure
Run agent-generated Python code securely via Azure Dynamic Sessions, with file upload and download support.
Why it matters
Empower your LLM agent to securely execute generated Python code within a low-latency Azure environment. This tool enables dynamic code interpretation and file management for complex tasks.
Outcomes
What it gets done
Run Python code generated by an LLM agent in a secure Azure sandbox.
Manage files within the execution environment, including listing, uploading, and downloading.
Integrate code execution capabilities into your existing LLM agent workflows.
Achieve low-latency code interpretation for faster agent responses.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/li-tool-tools-azure-code-interpreter | bash Overview
Azure Code Interpreter Tool
A LlamaIndex tool that runs agent-generated Python code in a secure, low-latency sandbox using Azure Container Apps Dynamic Sessions, with tools to list, upload, and download files in the session. Use it when an agent needs to execute arbitrary Python safely with low latency, backed by an Azure Dynamic Sessions pool. Requires an Azure Session Pool with the Session Pool Executor role assigned to your identity.
What it does
llama-index-tools-azure-code-interpreter gives a LlamaIndex agent the ability to run generated Python code in a secure, low-latency sandbox backed by an Azure Container Apps Dynamic Sessions Pool. The AzureCodeInterpreterToolSpec wraps that sandbox as four tools: code_interpreter sends Python code to the session and returns the output as JSON; list_files lists files available in the session under /mnt/data; upload_file uploads a file or data stream into the session under /mnt/data; and download_file pulls a file from that path back to the agent's host.
When to use - and when NOT to
Use this tool when an agent needs to execute arbitrary Python - calculations, data transforms, quick scripts - in an isolated, fast-starting environment rather than on the machine running the agent itself. It requires an existing Azure Dynamic Sessions Pool with a known poolManagementEndpoint, and the agent's identity (user email, service principal, or managed identity) must be granted the Session Pool Executor role in that pool's access control before code execution will succeed.
Inputs and outputs
code_interpreter takes a python_code string and returns a JSON result with stdout, stderr, result, and executionTimeInMilliseconds fields:
code_interpreter_spec = AzureCodeInterpreterToolSpec(
pool_management_endpoint=os.getenv("AZURE_POOL_MANAGEMENT_ENDPOINT")
)
agent = ReActAgent.from_tools(
code_interpreter_spec.to_tool_list(), llm=llm, verbose=True
)
list_files and upload_file/download_file operate against files under the session's /mnt/data path. list_files and code_interpreter are exposed to both the developer and the LLM agent in the tool spec, while upload_file and download_file are developer-only operations, not agent-callable tools. The project's own walkthrough shows a ReActAgent asked "Tell me the current time in Seattle": rather than guessing, the agent reasons that it needs the current UTC time adjusted for Seattle's timezone, calls code_interpreter with a short Python snippet using datetime and pytz, observes the JSON result (stdout, stderr, result, executionTimeInMilliseconds), and only then answers from that real output - illustrating that answers come from actual code execution, not LLM guesswork.
Integrations
Set the pool endpoint via an AZURE_POOL_MANAGEMENT_ENDPOINT environment variable, typically in a .env file, then wire the tool spec into any LlamaIndex agent - the project's own example uses a ReActAgent backed by AzureOpenAI. Install with pip install llama-index-tools-azure-code-interpreter. A more detailed walkthrough, covering the same setup end to end, is provided in the project's azure_code_interpreter Jupyter notebook.
Who it's for
Developers building LlamaIndex agents on Azure who need agents to run and act on the results of real Python execution - not just LLM-generated text - without managing their own sandboxing infrastructure.
Source README
Azure Code Interpreter Tool
This tool leverages Azure Dynamic Sessions Pool to enable an Agent to run generated Python code in a secure environment with very low latency.
In order to utilize the tool, you will need to have the Session Pool management endpoint first. Learn more
Prerequisites
Make sure to create a Session Pool and note down the
poolManagementEndpoint.In order to have the code execution right, the correct role needs to be assigned to the current user agent. Be sure to assign
Session Pool Executorrole to the correct user agent's identity (e.g. User Email, Service Principal, Managed Identity, etc.) in Session Pool's access control panel through the Portal or CLI. Learn more
Usage
A more detailed sample is located in a Jupyter notebook here
Here's an example usage of the AzureCodeInterpreterToolSpec.
- First, install the Azure Dynamic Sessions package using
pip:
pip install llama-index-tools-azure-code-interpreter
- Create a file named
.envin the same directory as your script with the following content:
AZURE_POOL_MANAGEMENT_ENDPOINT=<poolManagementEndpoint>
- Next, set up the Dynamic Sessions tool and a LLM agent:
from llama_index.tools.azure_code_interpreter import (
AzureCodeInterpreterToolSpec,
)
from llama_index.core.agent import ReActAgent
from llama_index.llms.azure_openai import AzureOpenAI
llm = AzureOpenAI(
model="gpt-35-turbo",
deployment_name="gpt-35-deploy",
api_key=api_key,
azure_endpoint=azure_endpoint,
api_version=api_version,
)
code_interpreter_spec = AzureCodeInterpreterToolSpec(
pool_management_endpoint=os.getenv("AZURE_POOL_MANAGEMENT_ENDPOINT")
)
agent = ReActAgent.from_tools(
code_interpreter_spec.to_tool_list(), llm=llm, verbose=True
)
- Use the tool as you need:
print(agent.chat("Tell me the current time in Seattle."))
"""
Sample Return:
Thought: To provide the current time in Seattle, I need to calculate it based on the current UTC time and adjust for Seattle's time zone, which is Pacific Daylight Time (PDT) during daylight saving time and Pacific Standard Time (PST) outside of daylight saving time. PDT is UTC-7, and PST is UTC-8. I can use the code interpreter tool to get the current UTC time and adjust it accordingly.
Action: code_interpreter
Action Input: {'python_code': "from datetime import datetime, timedelta; import pytz; utc_now = datetime.now(pytz.utc); seattle_time = utc_now.astimezone(pytz.timezone('America/Los_Angeles')); seattle_time.strftime('%Y-%m-%d %H:%M:%S %Z%z')"}
Observation: {'$id': '1', 'status': 'Success', 'stdout': '', 'stderr': '', 'result': '2024-05-04 13:54:09 PDT-0700', 'executionTimeInMilliseconds': 120}
Thought: I can answer without using any more tools. I'll use the user's language to answer.
Answer: The current time in Seattle is 2024-05-04 13:54:09 PDT.
The current time in Seattle is 2024-05-04 13:54:09 PDT.
"""
print(dynamic_session_tool.code_interpreter("1+1"))
"""
Sample Return:
{'$id': '1', 'status': 'Success', 'stdout': '', 'stderr': '', 'result': 2, 'executionTimeInMilliseconds': 11}
"""
Included Tools
The AzureCodeInterpreterToolSpec provides the following tools to the agent:
code_interpreter: (Available to developer and LLM Agent in tool spec) Send a Python code to be executed in Azure Container Apps Dynamic Sessions and return the output in a JSON format.
list_files: (Available to developer and LLM Agent in tool spec) List the files available in a Session under the path /mnt/data.
upload_file: (Available to developer) Upload a file or a stream of data into a Session under the path /mnt/data.
download_file: (Available to developer) Download a file by its path relative to the path /mnt/data to the tool's hosting agent.
FAQ
Common questions
Discussion
Questions & comments ยท 0
Sign In Sign in to leave a comment.