你的 AI 代理可以免费运行 Python。方法如下。

发布: (2026年2月3日 GMT+8 21:41)
4 分钟阅读
原文: Dev.to

Source: Dev.to

抱歉,您只提供了来源链接,未附上需要翻译的正文内容。请把要翻译的文本粘贴在这里,我会按照要求保留格式并翻译成简体中文。

What sandpy solves

  • Zero‑cost execution – 完全在客户端运行。
  • Safety – 超时防止无限循环卡住标签页。
  • Streaming output – 在结果打印时即时查看。
  • State persistence – 快照让你保存并恢复 Python 会话。
  • Visualization support – 自动捕获 Matplotlib 图表为 base64 图像。
  • Vision hook – 将生成的图像输入视觉模型(例如 GPT‑4V)。
  • Ready‑made integrations – 包含 LangChain 和 Vercel AI SDK 适配器。

安装

npm install sandpy

基本用法

import { Sandpy } from 'sandpy';

const sandbox = await Sandpy.create();
const result = await sandbox.run('print(2 + 2)');
console.log(result.stdout); // "4"

就是这样——Python 可以在浏览器中运行。

LangChain 集成

import { createLangChainTool } from 'sandpy';
import { DynamicTool } from 'langchain/tools';

const pythonTool = new DynamicTool(
  createLangChainTool({ timeout: 30_000 })
);

// Add to your agent
const agent = new Agent({
  tools: [pythonTool],
});

如果生成的代码出现异常,沙箱会超时而不是永远挂起。

Vercel AI SDK 集成

import { createVercelAITool } from 'sandpy';
import { generateText } from 'ai';

const pythonTool = createVercelAITool({ timeout: 30_000 });

const result = await generateText({
  model: yourModel,
  tools: { python: pythonTool },
  prompt: 'Calculate the first 20 Fibonacci numbers',
});

捕获可视化并使用视觉模型

当生成 Matplotlib 图时,sandbox 返回一个 base64 编码的图像,可以发送给视觉模型:

const result = await sandbox.run(plotCode, {
  describeArtifact: async (artifact) => {
    const response = await openai.chat.completions.create({
      model: 'gpt-4-vision-preview',
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: 'Describe this chart.' },
            {
              type: 'image_url',
              image_url: {
                url: `data:${artifact.type};base64,${artifact.content}`,
              },
            },
          ],
        },
      ],
    });
    return response.choices[0].message.content;
  },
});

artifact.alt 可能包含类似以下内容的描述:“一张显示从 0 到 100 的指数增长的折线图。”
你的代理随后可以根据该描述自行纠正。

文件系统与持久化

// Preload pandas (optional)
const sandbox = await Sandpy.create({ preload: ['pandas'] });

// Write a CSV file
await sandbox.writeFile('/sandbox/data.csv', csvContent);

// Read it from Python
const result = await sandbox.run(`
import pandas as pd
df = pd.read_csv('/sandbox/data.csv')
print(df.describe())
`);

位于 /sandbox/ 下的文件会通过 Origin‑Private File System (OPFS) 并使用 IndexedDB 作为后备,在页面重新加载后仍然存在。

快照与会话恢复

// Build some state
await sandbox.run('x = 42');
await sandbox.run('data = [1, 2, 3]');

// Save snapshot
const snapshot = await sandbox.snapshot();
localStorage.setItem('session', JSON.stringify(snapshot));

// Later (even after a refresh)
const saved = JSON.parse(localStorage.getItem('session'));
await sandbox.restore(saved);

await sandbox.run('print(x)'); // "42"

浏览器 vs. 服务器 沙箱比较

功能服务器沙箱浏览器沙箱
成本~ $0.10 / 会话免费
延迟网络往返即时
隐私代码发送到服务器保持在浏览器中
离线
规模按使用付费无限

对于面向消费者的 AI 代理,浏览器原生方式是合理的默认选择。

演示与来源

  • 实时演示:
  • GitHub 仓库:
  • npm 包: npm install sandpy

如果您需要为 AI 代理执行代码,试试 sandpy。欢迎在评论中提问。

Back to Blog

相关文章

阅读更多 »

当 AI 给你一巴掌

当 AI 给你当头一棒:在 Adama 中调试 Claude 生成的代码。你是否曾让 AI “vibe‑code” 一个复杂功能,却花了数小时调试细微的 bug……