跳转到内容
搜索文档

使用代码解释器

最后更新 查看 MarkdownAgent 设置

本指南说明如何使用 Code Interpreter API 执行带有丰富输出的 Python 和 JavaScript 代码。

何时使用代码解释器

简单、直接的代码执行使用 Code Interpreter API,只需最少配置:

  • 快速执行代码 - 无需环境配置即可运行 Python/JS 代码
  • 丰富输出 - 自动获取图表、表格、图像、HTML
  • AI 生成的代码 - 执行 LLM 生成的代码并获得结构化结果
  • 持久状态 - 同一上下文中的变量在多次执行之间保留

高级或自定义工作流使用 exec()

  • 系统操作 - 安装软件包、管理文件、运行构建
  • 自定义环境 - 配置特定版本和依赖
  • Shell 命令 - Git 操作、系统工具、复杂流水线
  • 长时间运行的进程 - 后台服务、服务器

创建执行上下文

代码上下文会在多次执行之间保持状态:

import { getSandbox } from "@cloudflare/sandbox";

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Create a Python context
const pythonContext = await sandbox.createCodeContext({
	language: "python",
});

console.log("Context ID:", pythonContext.id);
console.log("Language:", pythonContext.language);

// Create a JavaScript context
const jsContext = await sandbox.createCodeContext({
	language: "javascript",
});
import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(env.Sandbox, 'my-sandbox');

// Create a Python context
const pythonContext = await sandbox.createCodeContext({
  language: 'python'
});

console.log('Context ID:', pythonContext.id);
console.log('Language:', pythonContext.language);

// Create a JavaScript context
const jsContext = await sandbox.createCodeContext({
  language: 'javascript'
});

执行代码

简单执行

// Create context
const context = await sandbox.createCodeContext({
	language: "python",
});

// Execute code
const result = await sandbox.runCode(
	`
print("Hello from Code Interpreter!")
result = 2 + 2
print(f"2 + 2 = {result}")
`,
	{ context: context.id },
);

console.log("Output:", result.output);
console.log("Success:", result.success);
// Create context
const context = await sandbox.createCodeContext({
  language: 'python'
});

// Execute code
const result = await sandbox.runCode(`
print("Hello from Code Interpreter!")
result = 2 + 2
print(f"2 + 2 = {result}")
`, { context: context.id });

console.log('Output:', result.output);
console.log('Success:', result.success);

上下文内的状态

只要 container 保持活动,同一上下文中的变量和导入在多次执行之间仍然可用:

const context = await sandbox.createCodeContext({
	language: "python",
});

// First execution - import and define variables
await sandbox.runCode(
	`
import pandas as pd
import numpy as np

data = [1, 2, 3, 4, 5]
print("Data initialized")
`,
	{ context: context.id },
);

// Second execution - use previously defined variables
const result = await sandbox.runCode(
	`
mean = np.mean(data)
print(f"Mean: {mean}")
`,
	{ context: context.id },
);

console.log(result.output); // "Mean: 3.0"
const context = await sandbox.createCodeContext({
  language: 'python'
});

// First execution - import and define variables
await sandbox.runCode(`
import pandas as pd
import numpy as np

data = [1, 2, 3, 4, 5]
print("Data initialized")
`, { context: context.id });

// Second execution - use previously defined variables
const result = await sandbox.runCode(`
mean = np.mean(data)
print(f"Mean: {mean}")
`, { context: context.id });

console.log(result.output); // "Mean: 3.0"

处理丰富输出

代码解释器会返回多种输出格式:

const result = await sandbox.runCode(
	`
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Simple Chart')
plt.show()
`,
	{ context: context.id },
);

// Check available formats
console.log("Formats:", result.formats); // ['text', 'png']

// Access outputs
if (result.outputs.png) {
	// Return as image
	return new Response(atob(result.outputs.png), {
		headers: { "Content-Type": "image/png" },
	});
}

if (result.outputs.html) {
	// Return as HTML (pandas DataFrames)
	return new Response(result.outputs.html, {
		headers: { "Content-Type": "text/html" },
	});
}

if (result.outputs.json) {
	// Return as JSON
	return Response.json(result.outputs.json);
}
const result = await sandbox.runCode(`
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Simple Chart')
plt.show()
`, { context: context.id });

// Check available formats
console.log('Formats:', result.formats);  // ['text', 'png']

// Access outputs
if (result.outputs.png) {
  // Return as image
  return new Response(atob(result.outputs.png), {
    headers: { 'Content-Type': 'image/png' }
  });
}

if (result.outputs.html) {
  // Return as HTML (pandas DataFrames)
  return new Response(result.outputs.html, {
    headers: { 'Content-Type': 'text/html' }
  });
}

if (result.outputs.json) {
  // Return as JSON
  return Response.json(result.outputs.json);
}

流式执行输出

对于长时间运行的代码,可实时流式输出:

const context = await sandbox.createCodeContext({
	language: "python",
});

const result = await sandbox.runCode(
	`
import time

for i in range(10):
    print(f"Processing item {i+1}/10...")
    time.sleep(0.5)

print("Done!")
`,
	{
		context: context.id,
		stream: true,
		onOutput: (data) => {
			console.log("Output:", data);
		},
		onResult: (result) => {
			console.log("Result:", result);
		},
		onError: (error) => {
			console.error("Error:", error);
		},
	},
);
const context = await sandbox.createCodeContext({
  language: 'python'
});

const result = await sandbox.runCode(
  `
import time

for i in range(10):
    print(f"Processing item {i+1}/10...")
    time.sleep(0.5)

print("Done!")
`,
  {
    context: context.id,
    stream: true,
    onOutput: (data) => {
      console.log('Output:', data);
    },
    onResult: (result) => {
      console.log('Result:', result);
    },
    onError: (error) => {
      console.error('Error:', error);
    }
  }
);

执行 AI 生成的代码

在沙箱中安全运行 LLM 生成的代码:

// 1. Generate code with Claude
const response = await fetch("https://api.anthropic.com/v1/messages", {
	method: "POST",
	headers: {
		"Content-Type": "application/json",
		"x-api-key": env.ANTHROPIC_API_KEY,
		"anthropic-version": "2023-06-01",
	},
	body: JSON.stringify({
		model: "claude-3-5-sonnet-20241022",
		max_tokens: 1024,
		messages: [
			{
				role: "user",
				content: "Write Python code to calculate fibonacci sequence up to 100",
			},
		],
	}),
});

const { content } = await response.json();
const code = content[0].text;

// 2. Execute in sandbox
const context = await sandbox.createCodeContext({ language: "python" });
const result = await sandbox.runCode(code, { context: context.id });

console.log("Generated code:", code);
console.log("Output:", result.output);
console.log("Success:", result.success);
// 1. Generate code with Claude
const response = await fetch('https://api.anthropic.com/v1/messages', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': env.ANTHROPIC_API_KEY,
    'anthropic-version': '2023-06-01'
  },
  body: JSON.stringify({
    model: 'claude-3-5-sonnet-20241022',
    max_tokens: 1024,
    messages: [{
      role: 'user',
      content: 'Write Python code to calculate fibonacci sequence up to 100'
    }]
  })
});

const { content } = await response.json();
const code = content[0].text;

// 2. Execute in sandbox
const context = await sandbox.createCodeContext({ language: 'python' });
const result = await sandbox.runCode(code, { context: context.id });

console.log('Generated code:', code);
console.log('Output:', result.output);
console.log('Success:', result.success);

管理上下文

列出所有上下文

const contexts = await sandbox.listCodeContexts();

console.log(`${contexts.length} active contexts:`);

for (const ctx of contexts) {
	console.log(`  ${ctx.id} (${ctx.language})`);
}
const contexts = await sandbox.listCodeContexts();

console.log(`${contexts.length} active contexts:`);

for (const ctx of contexts) {
  console.log(`  ${ctx.id} (${ctx.language})`);
}

删除上下文

// Delete specific context
await sandbox.deleteCodeContext(context.id);
console.log("Context deleted");

// Clean up all contexts
const contexts = await sandbox.listCodeContexts();
for (const ctx of contexts) {
	await sandbox.deleteCodeContext(ctx.id);
}
console.log("All contexts deleted");
// Delete specific context
await sandbox.deleteCodeContext(context.id);
console.log('Context deleted');

// Clean up all contexts
const contexts = await sandbox.listCodeContexts();
for (const ctx of contexts) {
  await sandbox.deleteCodeContext(ctx.id);
}
console.log('All contexts deleted');

最佳实践

  • 清理上下文 - 完成后删除上下文以释放资源
  • 处理错误 - 始终检查 result.successresult.error
  • 长时间操作使用流式输出 - 对耗时超过 2 秒的代码使用流式输出
  • 校验 AI 代码 - 执行前审查生成的代码

相关资源

这篇文档对您有帮助吗?