云沙箱 Code Interpreter 当前只支持文件降级方案:在 Sandbox 内生成图表文件,再通过 Filesystem 取回。不要依赖 execution.results[].png 或 execution.results[].chart 作为正式接入路径。
生成图片文件
使用 Matplotlib 生成图表时,把图片保存到 Sandbox 内的固定路径:
sandbox.run_code("""import matplotlib.pyplot as plt; plt.plot([1, 2, 3], [1, 4, 9]);plt.savefig("/tmp/chart.png")""")TypeScript 示例:
await sandbox.runCode(`import matplotlib.pyplot as plt; plt.plot([1, 2, 3], [1, 4, 9]); plt.savefig("/tmp/chart.png")`);随后读取文件内容:
content = sandbox.files.read("/tmp/chart.png", format="bytes")TypeScript 示例:
const content = await sandbox.files.read("/tmp/chart.png", { format: "bytes" });也可以用上传下载地址把图片交给浏览器或下游系统:
download_url = sandbox.download_url("/tmp/chart.png")TypeScript 示例:
const downloadUrl = await sandbox.downloadUrl("/tmp/chart.png");生成多张图
多张图应使用稳定文件名,避免覆盖:
sandbox.run_code("""import matplotlib.pyplot as plt; plt.figure(); plt.plot([1, 2, 3]); plt.savefig("/tmp/chart-1.png"); plt.figure(); plt.bar(["A", "B"], [10, 20]); plt.savefig("/tmp/chart-2.png")""")TypeScript 示例:
await sandbox.runCode(`import matplotlib.pyplot as plt; plt.figure(); plt.plot([1, 2, 3]); plt.savefig("/tmp/chart-1.png"); plt.figure(); plt.bar(["A", "B"], [10, 20]); plt.savefig("/tmp/chart-2.png")`);然后分别读取或下载 /tmp/chart-1.png 和 /tmp/chart-2.png。
使用建议
提示 AI 生成代码时,要求使用
plt.savefig(),不要要求plt.show()。约定输出目录和文件名,例如
/tmp/chart.png或/tmp/charts/chart-1.png。需要长期保存时,把图片写入 OSS、数据库或业务文件存储。
对用户可见的图片,业务侧应校验文件大小和 MIME 类型。
该文章对您有帮助吗?