Back to Pandas Ai

Execute code in a sandbox

examples/docker_sandbox.ipynb

3.0.02.5 KB
Original Source

Execute code in a sandbox

To enhance security and protect yourself from malicious code through prompt injection, we make it possible to run code in a sandbox environment. This notebook explains how to do it.

Install the package

First of all you need to install the python package. You can use pip to install it

python
%pip install pandasai-docker

Execute the code in the sandbox

Please keep in mind the sandbox works offline. Once you have installed the package, you can start the sandbox with the following code.

python
import pandasai as pai
from pandasai_docker import DockerSandbox
from pandasai_litellm.litellm import LiteLLM

# Initialize LiteLLM with your OpenAI model
llm = LiteLLM(model="gpt-4.1-mini", api_key="YOUR_OPENAI_API_KEY")

# Configure PandasAI to use this LLM
pai.config.set({
    "llm": llm
})

# initialize the sandbox
sandbox = DockerSandbox()
sandbox.start()

# read a csv as df
df = pai.read_csv("./data/heart.csv")

# pass the csv and the sandbox to the agent
result = pai.chat("plot total heart patients by gender", df, sandbox=sandbox)

result.show()

# stop the sandbox (docker container)
sandbox.stop()

Execute the code in the sandbox with the agent

Please keep in mind the sandbox works offline. Once you have installed the package, you can start the sandbox with the following code.

python
import pandasai as pai
from pandasai import Agent
from pandasai_docker import DockerSandbox
from pandasai_litellm.litellm import LiteLLM

# Initialize LiteLLM with your OpenAI model
llm = LiteLLM(model="gpt-4.1-mini", api_key="YOUR_OPENAI_API_KEY")

# Configure PandasAI to use this LLM
pai.config.set({
    "llm": llm
})

# initialize the sandbox
sandbox = DockerSandbox()
sandbox.start()

# read a csv as df
df = pai.read_csv("./data/heart.csv")

# pass the csv and the sandbox to the agent
agent = Agent([df], memory_size=10, sandbox=sandbox)

# Chat with the Agent
response = agent.chat("plot top five artists streams")

# stop the sandbox (docker container)
sandbox.stop()

Customize the sandbox

You can decide the name and path of your sandbox by passing them as positional arguments in the DockerSandbox()

python
sandbox = DockerSandbox("PandasAI-sandbox", "/path/to/Dockerfile")

# read a csv as df
df = pai.read_csv("./data/heart.csv")

# pass the csv and the sandbox to the agent
agent = Agent([df], memory_size=10, sandbox=sandbox)

# Chat with the Agent
response = agent.chat("plot top five artists streams")

sandbox.stop()