PandasAI v3 移除 custom_whitelisted_dependencies 后如何用 Docker 沙箱替代
【免费下载链接】pandas-aiChat with your database or your datalake (SQL, CSV, parquet). PandasAI makes data analysis conversational using LLMs and RAG.项目地址: https://gitcode.com/GitHub_Trending/pa/pandas-ai
如果你在 v2 里用custom_whitelisted_dependencies给 PandasAI 的 LLM 代码执行加了自定义模块,升级到 v3 后会发现这个配置项已经被删除——v3 明确用沙箱环境(sandbox environment)来处理代码执行安全。这篇文章面向正在做 v2 到 v3 迁移的开发者:任务是把依赖白名单配置的旧应用改造成 v3 写法,并让 LLM 生成的代码在 Docker 沙箱中运行。适用前提:系统上已安装并在运行 Docker,项目里已配置好 LLM(文中示例使用pandasai-litellm扩展)。
custom_whitelisted_dependencies 在 v2 与 v3 中的差别
v2 的默认白名单模块为pandas、numpy、matplotlib、seaborn、datetime、json、base64,实例化Agent时可通过custom_whitelisted_dependencies参数追加模块,模块必须已安装在 PandasAI 运行的环境中(见 v2 自定义白名单文档)。v2 文档同时给出了关键限制:
PandasAI cannot sandbox arbitrary code execution for custom libraries that are whitelisted.
也就是说,被加入白名单的库等于完全不受沙箱约束,可以执行任意代码。这正是 v3 移除该配置项的原因。
v3 的 迁移指南 在“Breaking Changes / Configuration”一节列出了被删除的配置项:
save_charts, enable_cache, security, custom_whitelisted_dependencies, save_charts_path, custom_head并说明了替代方向:“Security handled through sandbox environment”。迁移步骤的 Step 7 也要求把custom_whitelisted_dependencies、security等旧配置从代码中删掉,只保留 v3 的全局配置:
pai.config.set({ "llm": llm, "save_logs": True, "verbose": False, "max_retries": 3 })所以迁移路径是固定的两步:删掉旧白名单配置,改用 Docker 沙箱承载 LLM 生成代码的执行。
准备条件
按 隐私与安全文档 和 Agent 文档 的要求,使用前需要:
- 本机安装 Docker 并确保它正在运行(文档明确要求:Make sure you have Docker running on your system before using the sandbox environment)。
- 安装 PandasAI 本体和 LLM 扩展:
pip install pandasai pandasai-litellm- 安装沙箱扩展:
pip install pandasai-docker沙箱扩展的 README 也给出 poetry 安装方式:poetry add pandasai-docker。
配置全局设置并启用沙箱
v3 的配置是全局的,pai.config.set()对所有 DataFrame 生效,不再有 per-dataframe 的config参数。完整的最小示例来自 隐私与安全文档:
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 df and the sandbox result = pai.chat("plot total heart patients by gender", df, sandbox=sandbox) # display the chart result.show() # stop the sandbox (docker container) sandbox.stop()代码中需要替换的只有两处:api_key换成你自己的 LLM 密钥;./data/heart.csv换成你要分析的本地 CSV 相对路径(仓库 examples/data/heart.csv 有一份同名样例数据可参考)。
各步骤的判断依据:
pai.config.set()是 v3 唯一的全局配置入口,若配置不生效,迁移排查文档 指出应确认改用pai.config.set(config)而不是 v2 的SmartDataframe(data, config=config)写法;pai.chat(..., sandbox=sandbox)传入沙箱后,LLM 生成的代码在隔离的 Docker 容器内执行,而不是在宿主机上直接跑;result.show()能正常渲染出图表,说明这次带沙箱的问答走通了;- 用完后必须调用
sandbox.stop()停掉容器,否则会遗留一个常驻的 sandbox 容器。
文档列出的沙箱特性包括:代码在完全隔离的 Docker 容器内执行(Isolated Execution)、沙箱全程离线运行、阻断任何外部网络请求(Offline Operation)、严格的系统资源控制(Resource Limitations)、文件系统隔离(File System Isolation)。离线这一点要注意:沙箱内的代码无法访问外网,如果你的分析代码原本依赖下载资源,这条路不成立。
文档建议在这些场景下使用沙箱:构建面向公众的应用、处理不可信的用户输入、生产环境部署、处理敏感数据、多租户环境。
在 Agent 中替代 v2 的白名单配置
如果你的 v2 代码是通过Agent(df, config={"custom_whitelisted_dependencies": [...]})挂白名单的,v3 对应写法是把沙箱传给Agent,示例来自 Agent 文档:
from pandasai import Agent from pandasai_docker import DockerSandbox # Initialize the sandbox sandbox = DockerSandbox() sandbox.start() # Create an agent with the sandbox df = pai.read_csv("data.csv") agent = Agent([df], sandbox=sandbox) # Chat with the agent - code will run in the sandbox response = agent.chat("Calculate the average sales") # Don't forget to stop the sandbox when done sandbox.stop()Agent本身在 v3 中保持不变,只是移除了clarification_questions()、rephrase_query()、explain()三个方法,多轮场景用follow_up()代替(见 迁移指南)。
如果默认沙箱镜像不满足需求,Agent 文档给出了自定义入口:指定自定义镜像名和自定义 Dockerfile:
sandbox = DockerSandbox( "custom-sandbox-name", "/path/to/custom/Dockerfile" )第二个参数需要你替换为自己机器上某个 Dockerfile 的路径,文档没有提供具体的自定义 Dockerfile 内容,只能给出签名。
默认镜像里装了什么,可以看扩展自带的 Dockerfile:基础镜像为python:3.9,只安装了pandas、numpy、matplotlib,工作目录/app,容器命令为sleep infinity保持存活。对照 v2 的默认白名单(含seaborn、datetime、json、base64),可以据此判断你的分析代码能否直接在默认沙箱里跑:依赖pandas/numpy/matplotlib的没问题,依赖其他第三方库的要么改代码,要么按上一节的方式换成自建 Dockerfile。另外,沙箱代码中执行 SQL 时,查询结果会被转成 CSV 文件传入容器处理(见 docker_sandbox.py 中transfer_file相关实现),SQL 查询本身在宿主侧完成,这一点与“容器完全离线”并不矛盾。
验证迁移结果
迁移指南给出了迁移后的验证用例,可直接作为沙箱改造后的回归测试(Basic Chat Test):
import pandasai as pai import pandas as pd df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) df = pai.DataFrame(df) response = df.chat("What is the sum of x?") print(response)判断标准:
- 代码里不再出现
custom_whitelisted_dependencies、security、enable_cache等 v2 配置项,且用pai.config.set()完成全局配置后程序无异常; - 带
sandbox=sandbox的pai.chat/agent.chat能返回结果,result.show()能展示图表; - 结束时
sandbox.stop()成功停掉容器,无遗留的 sandbox 容器。
若出现ModuleNotFoundError: No module named 'pandasai.llm',这是 v2 导入路径残留,安装pandasai-litellm并改用 LLM 扩展 的导入方式即可,具体对照见 迁移排查文档。
限制
- 沙箱是 v3 的替代方案,但它不等同于 v2 的“白名单 + 信任库”模式:默认镜像只带
pandas、numpy、matplotlib,v2 白名单里的seaborn等模块不会自动出现在沙箱中。 - 沙箱容器离线运行,容器内代码不能发起外部网络请求。
- 使用沙箱前 Docker 必须处于运行状态,文档未提供更细的错误排查顺序,遇到容器级报错时先确认 Docker 服务状态与
pandasai-docker是否安装成功。 - 生产环境若需要自定义安全策略、高级资源管理、增强监控等能力,文档将其归为企业版(Enterprise license)提供的沙箱选项,见 隐私与安全文档 的 Enterprise Sandbox Options 一节。
【免费下载链接】pandas-aiChat with your database or your datalake (SQL, CSV, parquet). PandasAI makes data analysis conversational using LLMs and RAG.项目地址: https://gitcode.com/GitHub_Trending/pa/pandas-ai
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考