examples/docker_sandbox.ipynb
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.
First of all you need to install the python package. You can use pip to install it
%pip install pandasai-docker
Please keep in mind the sandbox works offline. Once you have installed the package, you can start the sandbox with the following code.
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()
Please keep in mind the sandbox works offline. Once you have installed the package, you can start the sandbox with the following code.
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()
You can decide the name and path of your sandbox by passing them as positional arguments in the DockerSandbox()
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()