跳转到内容
搜索文档

代码解释器

最后更新 查看 MarkdownAgent 设置

执行 Python、JavaScript 和 TypeScript 代码,支持数据可视化、表格和丰富输出格式。上下文会在多次执行之间保持状态(变量、导入、函数)。

方法

createCodeContext()

创建用于运行代码的持久执行上下文。

const context = await sandbox.createCodeContext(options?: CreateContextOptions): Promise<CodeContext>

参数

  • options(可选):
    • language - "python" | "javascript" | "typescript"(默认:"python"
    • cwd - 工作目录(默认:"/workspace"
    • envVars - 环境变量
    • timeout - 请求超时(毫秒,默认:30000)

返回:带有 idlanguagecwdcreatedAtlastUsedPromise<CodeContext>

const ctx = await sandbox.createCodeContext({
	language: "python",
	envVars: { API_KEY: env.API_KEY },
});
const ctx = await sandbox.createCodeContext({
  language: 'python',
  envVars: { API_KEY: env.API_KEY }
});

runCode()

在上下文中执行代码并返回完整结果。

const result = await sandbox.runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>

参数

  • code - 要执行的代码(必需)
  • options(可选):
    • context - 运行所用的上下文(推荐,见下文)
    • language - "python" | "javascript" | "typescript"(默认:"python"
    • timeout - 执行超时(毫秒,默认:60000)
    • onStdoutonStderronResultonError - 流式回调

返回:带有以下字段的 Promise<ExecutionResult>

  • code - 已执行的代码
  • logs - stdoutstderr 数组
  • results - 丰富输出数组(参见富输出格式
  • error - 执行错误(如有)
  • executionCount - 执行计数器

推荐用法 - 显式创建上下文

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

await sandbox.runCode("import math; radius = 5", { context: ctx });
const result = await sandbox.runCode("math.pi * radius ** 2", { context: ctx });

console.log(result.results[0].text); // "78.53981633974483"
const ctx = await sandbox.createCodeContext({ language: 'python' });

await sandbox.runCode('import math; radius = 5', { context: ctx });
const result = await sandbox.runCode('math.pi * radius ** 2', { context: ctx });

console.log(result.results[0].text); // "78.53981633974483"

错误处理

const result = await sandbox.runCode("x = 1 / 0", { language: "python" });

if (result.error) {
	console.error(result.error.name); // "ZeroDivisionError"
	console.error(result.error.value); // "division by zero"
	console.error(result.error.traceback); // Stack trace array
}
const result = await sandbox.runCode('x = 1 / 0', { language: 'python' });

if (result.error) {
  console.error(result.error.name);      // "ZeroDivisionError"
  console.error(result.error.value);     // "division by zero"
  console.error(result.error.traceback); // Stack trace array
}

JavaScript 和 TypeScript 特性

JavaScript 和 TypeScript 代码执行支持顶层 await,以及同一上下文中多次执行之间的持久变量。

const ctx = await sandbox.createCodeContext({ language: "javascript" });

// Execution 1: Fetch data with top-level await
await sandbox.runCode(
	`
const response = await fetch('https://api.example.com/data');
const data = await response.json();
`,
	{ context: ctx },
);

// Execution 2: Use the data from previous execution
const result = await sandbox.runCode("console.log(data)", { context: ctx });
console.log(result.logs.stdout); // Data persists across executions
const ctx = await sandbox.createCodeContext({ language: 'javascript' });

// Execution 1: Fetch data with top-level await
await sandbox.runCode(`
const response = await fetch('https://api.example.com/data');
const data = await response.json();
`, { context: ctx });

// Execution 2: Use the data from previous execution
const result = await sandbox.runCode('console.log(data)', { context: ctx });
console.log(result.logs.stdout); // Data persists across executions

使用 constletvar 声明的变量会在多次执行之间保留,从而支持多步骤工作流:

const ctx = await sandbox.createCodeContext({ language: "javascript" });

await sandbox.runCode("const x = 10", { context: ctx });
await sandbox.runCode("let y = 20", { context: ctx });
const result = await sandbox.runCode("x + y", { context: ctx });

console.log(result.results[0].text); // "30"
const ctx = await sandbox.createCodeContext({ language: 'javascript' });

await sandbox.runCode('const x = 10', { context: ctx });
await sandbox.runCode('let y = 20', { context: ctx });
const result = await sandbox.runCode('x + y', { context: ctx });

console.log(result.results[0].text); // "30"

listCodeContexts()

列出所有活动的代码执行上下文。

const contexts = await sandbox.listCodeContexts(): Promise<CodeContext[]>
const contexts = await sandbox.listCodeContexts();
console.log(`Found ${contexts.length} contexts`);
const contexts = await sandbox.listCodeContexts();
console.log(`Found ${contexts.length} contexts`);

deleteCodeContext()

删除代码执行上下文并释放其资源。

await sandbox.deleteCodeContext(contextId: string): Promise<void>
const ctx = await sandbox.createCodeContext({ language: "python" });
await sandbox.runCode('print("Hello")', { context: ctx });
await sandbox.deleteCodeContext(ctx.id);
const ctx = await sandbox.createCodeContext({ language: 'python' });
await sandbox.runCode('print("Hello")', { context: ctx });
await sandbox.deleteCodeContext(ctx.id);

富输出格式

结果包括:texthtmlpngjpegsvglatexmarkdownjsonchartdata

图表(matplotlib)

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

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.show()
`,
	{ language: "python" },
);

if (result.results[0]?.png) {
	const imageBuffer = Buffer.from(result.results[0].png, "base64");
	return new Response(imageBuffer, {
		headers: { "Content-Type": "image/png" },
	});
}
const result = await sandbox.runCode(`
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.show()
`, { language: 'python' });

if (result.results[0]?.png) {
  const imageBuffer = Buffer.from(result.results[0].png, 'base64');
  return new Response(imageBuffer, {
    headers: { 'Content-Type': 'image/png' }
  });
}

表格(pandas)

const result = await sandbox.runCode(
	`
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df
`,
	{ language: "python" },
);

if (result.results[0]?.html) {
	return new Response(result.results[0].html, {
		headers: { "Content-Type": "text/html" },
	});
}
const result = await sandbox.runCode(`
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df
`, { language: 'python' });

if (result.results[0]?.html) {
  return new Response(result.results[0].html, {
    headers: { 'Content-Type': 'text/html' }
  });
}

相关资源

这篇文档对您有帮助吗?