关于 code-interpreter
基于 AWS Bedrock AgentCore Code Interpreter 的沙箱代码执行技能,适用于需要实际运行代码的测试、数据分析和原型开发。它提供代码与 Shell 执行,并在会话工作区中保留文件。
主要功能
- 01运行 Python、JavaScript 和 TypeScript
- 02执行 Shell 命令
- 03读取、写入、列出和删除文件
- 04持久化会话工作区
- 05发布生成的文件
适用场景
- 01测试和调试代码片段
- 02探索数据并生成分析结果
- 03开发算法原型
- 04安装和检查软件包
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ aws-samples/ sample-strands-agent-with-agentcore --skill code-interpreter安装后在 Claude Code 中输入/code-interpreter确认已加载。
详细介绍
代码解释器
由 AWS Bedrock AgentCore Code Interpreter 提供支持的通用代码执行环境。可在安全沙箱中运行代码、执行 Shell 命令并管理文件。
可用工具
- execute_code(code, language, output_filename):执行 Python、JavaScript 或 TypeScript 代码。
- execute_command(command):执行 Shell 命令。
- file_operations(operation, paths, content):读取、写入、列出或删除已挂载会话工作区中的文件。
工具参数
execute_code
| 参数 | 类型 | 必填 | 默认值 | 描述 |
|---|---|---|---|---|
code | string | 是 | 要执行的代码。使用 print() 输出文本。 | |
language | string | 否 | "python" | "python"、"javascript" 或 "typescript" |
output_filename | string | 否 | "" | 要发布为持久会话文件的文件。代码必须保存一个名称完全匹配的文件。 |
execute_command
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
command | string | 是 | 要执行的 Shell 命令(例如,"ls -la"、"pip install requests")。 |
file_operations
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
operation | string | 是 | "read"、"write"、"list" 或 "remove" |
paths | list | 对 read/list/remove 必填 | 文件路径。read:["file.txt"],list:["."],remove:["old.txt"] |
content | list | 对 write 必填 | 包含 path 和 text 的条目:[{"path": "out.txt", "text": "hello"}] |
tool_input 示例
execute_code — 文本输出
{
"code": "import pandas as pd\ndf = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})\nprint(df.describe())",
"language": "python"
}
execute_code — 生成图表
{
"code": "import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 10, 100)\nplt.figure(figsize=(10,6))\nplt.plot(x, np.sin(x))\nplt.title('Sine Wave')\nplt.savefig('sine.png', dpi=300, bbox_inches='tight')\nprint('Done')",
"language": "python",
"output_filename": "sine.png"
}
execute_command — 安装软件包
{
"command": "pip install yfinance"
}
execute_command — 检查环境
{
"command": "python --version && pip list | head -20"
}
file_operations — 写入文件
{
"operation": "write",
"content": [{"path": "config.json", "text": "{\"key\": \"value\"}"}]
}
file_operations — 列出文件
{
"operation": "list",
"paths": ["."]
}
file_operations — 读取文件
{
"operation": "read",
"paths": ["output.csv"]
}
何时使用此技能
将 code-interpreter 用作测试和原型设计代码的沙箱。 对于生产任务(创建文档、图表、演示文稿),优先使用专用技能。
不要用于:
- 格式化或展示代码示例(直接用 Markdown 代码块回复)
- 解释代码或算法(直接用文本回复)
- 可以心算的简单计算(直接给出答案)
- 不需要实际执行代码的任何任务
| 任务 | 推荐技能 | 备注 |
|---|---|---|
| 创建图表/示意图 | visual-design | 生产级图表优先使用此技能 |
| 创建 Word 文档 | word-documents | 支持模板和样式设置 |
| 创建 Excel 电子表格 | excel-spreadsheets | 提供格式处理流程和验证 |
| 创建 PowerPoint | powerpoint-presentations | 具有布局系统和设计模式 |
| 测试代码片段 | code-interpreter | 调试、验证逻辑、检查输出 |
| 原型设计算法 | code-interpreter | 在实现前进行试验 |
| 安装/测试软件包 | code-interpreter | 检查兼容性、测试 API |
| 调试代码逻辑 | code-interpreter | 隔离并测试特定函数 |
| 验证计算 | code-interpreter | 快速进行数学或数据检查 |
代码解释器与代码 Agent 的对比
| 代码解释器 | 代码 Agent | |
|---|---|---|
| 性质 | 沙箱执行环境 | 自主 Agent(Claude Code) |
| 最适合 | 快速脚本、数据分析、原型设计 | 多文件项目、重构、测试套件 |
| 文件持久性 | /mnt/workspace 中的文件会在解释器重启后保留 | 所有文件都会自动同步到 S3 |
| 会话状态 | 变量在单个解释器会话中保留;工作区文件在整个聊天会话中保留 | 文件和对话会跨会话保留 |
| 自主性 | 由你编写代码 | Agent 负责规划、编写、运行并迭代 |
| 适用场景 | 需要运行特定代码片段时 | 需要工程师端到端解决问题时 |
工作区集成
聊天会话在 /mnt/workspace 挂载了持久化文件系统。
Code Interpreter 工具使用的相对文件路径会解析到此目录中。
写入该目录的文件属于临时文件,并会在解释器会话重启后继续保留。除非提供
output_filename,否则这些文件不会成为用户可下载的产物。
必须进行挂载。如果无法配置或附加挂载,Code Interpreter 会返回错误,而不会启动 隔离的非持久化会话。
直接创建持久化文件:
{
"tool": "execute_code",
"code": "from pathlib import Path\nPath('/mnt/workspace/results.json').write_text('{\"ok\": true}')"
}
生成的文件必须显示在 Generated Files 中或供用户下载时,请使用
output_filename。工具会在返回成功前发布并验证该文件。不要创建指向 /mnt/workspace 的 Markdown 链接,也不要将
原始工作区路径描述为下载链接;应用会呈现文件操作。
上传的文件:
用户上传的文件无需手动加载或进行 Base64 传输,即可在挂载的工作区 /mnt/workspace/inputs 中访问。JSON、JSONL 和 NDJSON 附件可能会在对话中以受限文本摘录的形式呈现;需要完整数据集时,请使用挂载的文件。
使用 file_operations 检查临时文件。已发布的文件会显示在应用中,应使用其显示的文件名进行引用。
环境
- 语言: Python(推荐,包含 200 多个库)、JavaScript、TypeScript
- Shell: 通过
execute_command完整访问 Shell - 文件系统:
/mnt/workspace在聊天会话的 Code Interpreter 重启后仍会保留 - 会话状态: 变量在同一解释器会话中保留;文件会保留在挂载的工作区中
- 网络: 可访问互联网(可使用
requests、urllib、curl)
支持的语言
- Python(推荐)——预装 200 多个库,涵盖数据科学、机器学习、可视化和文件处理
- JavaScript——Node.js 运行时,适用于 JSON 处理和异步操作
- TypeScript——支持类型检查的 TypeScript 运行时
预装的 Python 库
数据分析与可视化
| 库 | 常见用途 |
|---|---|
pandas | DataFrame、CSV/Excel 输入输出、分组、透视 |
numpy | 数组、线性代数、随机数、统计 |
matplotlib | 折线图、柱状图、散点图、直方图、子图 |
plotly | 交互式图表、3D 图 |
bokeh | 交互式可视化 |
scipy | 优化、插值、信号处理 |
statsmodels | 回归、时间序列、假设检验 |
sympy | 代数、微积分、方程求解 |
机器学习与 AI
| 库 | 常见用途 |
|---|---|
scikit-learn | 分类、回归、聚类、流水线 |
torch / torchvision / torchaudio | 深度学习、计算机视觉、音频 |
xgboost | 高性能梯度提升 |
spacy / nltk / textblob | NLP、分词、NER、情感分析 |
scikit-image | 图像处理、滤镜、分割 |
数学与优化
| 库 | 常见用途 |
|---|---|
cvxpy | 凸优化、投资组合优化 |
ortools | 调度、路径规划、约束编程 |
pulp | 线性规划 |
z3-solver | SAT 求解、形式化验证 |
networkx / igraph | 图算法、网络分析 |
文件处理与文档
| 库 | 常见用途 |
|---|---|
openpyxl / xlrd / XlsxWriter | 带格式的 Excel 读写 |
python-docx | Word 文档创建与修改 |
python-pptx | PowerPoint 创建与修改 |
PyPDF2 / pdfplumber / reportlab | PDF 读取、写入与生成 |
lxml / beautifulsoup4 | XML/HTML 解析 |
markitdown | 将各种格式转换为 Markdown |
图像与媒体
| 库 | 常见用途 |
|---|---|
pillow (PIL) | 图像缩放、裁剪、滤镜、转换 |
opencv-python (cv2) | 计算机视觉、特征检测 |
imageio / moviepy | 图像/视频读写与编辑 |
pydub | 音频处理 |
svgwrite / Wand | SVG 创建、ImageMagick |
数据存储与格式
| 库 | 常见用途 |
|---|---|
duckdb | 对 DataFrame 和文件执行 SQL 查询 |
SQLAlchemy | SQL ORM 和数据库抽象 |
pyarrow | Parquet 和 Arrow 格式处理 |
orjson / ujson / PyYAML | 快速解析 JSON/YAML |
Web 与 API
| 库 | 常见用途 |
|---|---|
requests / httpx | HTTP 请求、API 调用 |
beautifulsoup4 | 网页抓取 |
fastapi / Flask / Django | Web 框架 |
实用工具
| 库 | 常见用途 |
|---|---|
pydantic | 数据验证、模式定义 |
Faker | 测试数据生成 |
rich | 美化输出、表格 |
cryptography | 加密、哈希 |
qrcode | QR 码生成 |
boto3 | AWS SDK |
如需查看包含版本号的 200 多个库的完整列表,请运行:
execute_command(command="pip list")
使用模式
模式 1:数据分析
import pandas as pd
import numpy as np
df = pd.DataFrame({
'date': pd.date_range('2024-01-01', periods=100),
'revenue': np.random.normal(1000, 200, 100),
'costs': np.random.normal(700, 150, 100),
})
df['profit'] = df['revenue'] - df['costs']
print("=== Summary Statistics ===")
print(df.describe())
print(f"\nTotal Profit: ${df['profit'].sum():,.2f}")
print(f"Profit Margin: {df['profit'].mean() / df['revenue'].mean() * 100:.1f}%")
模式 2:可视化(使用 output_filename)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
categories = ['Q1', 'Q2', 'Q3', 'Q4']
values = [120, 150, 180, 210]
axes[0,0].bar(categories, values, color='#2196F3')
axes[0,0].set_title('Quarterly Revenue')
x = np.linspace(0, 10, 50)
axes[0,1].plot(x, np.sin(x), 'b-', linewidth=2)
axes[0,1].set_title('Trend')
sizes = [35, 30, 20, 15]
axes[1,0].pie(sizes, labels=['A','B','C','D'], autopct='%1.1f%%')
axes[1,0].set_title('Market Share')
x = np.random.normal(50, 10, 200)
y = x * 1.5 + np.random.normal(0, 15, 200)
axes[1,1].scatter(x, y, alpha=0.5, c='#FF5722')
axes[1,1].set_title('Correlation')
plt.tight_layout()
plt.savefig('dashboard.png', dpi=300, bbox_inches='tight')
print('Dashboard saved')
模式 3:机器学习
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.datasets import load_iris
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42
)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred, target_names=iris.target_names))
模式 4:使用 DuckDB 执行 SQL
import duckdb
import pandas as pd
orders = pd.DataFrame({
'order_id': range(1, 101),
'customer': [f'Customer_{i%20}' for i in range(100)],
'amount': [round(50 + i * 3.5, 2) for i in range(100)],
})
result = duckdb.sql("""
SELECT customer, COUNT(*) as cnt, ROUND(SUM(amount), 2) as total
FROM orders GROUP BY customer
HAVING COUNT(*) >= 3 ORDER BY total DESC LIMIT 10
""").df()
print(result.to_string(index=False))
模式 5:从 Web 获取数据
import requests
import pandas as pd
response = requests.get("https://api.example.com/data")
data = response.json()
df = pd.DataFrame(data)
print(df.head())
模式 6:多步工作流(会话状态会保留)
Call 1: execute_code → load and clean data, store in variable `df`
Call 2: execute_code → analyze `df`, generate chart, save as PNG
Call 3: execute_code → export results to CSV
Call 4: file_operations(operation="read") → download the CSV
同一会话中的变量(df)和文件会在多次调用之间保留。
重要规则
- 在
import matplotlib.pyplot之前调用matplotlib.use('Agg')— 沙盒没有显示设备。 - 使用
print()输出文本 — 结果通过 stdout 返回。 output_filename必须完全匹配 —plt.savefig()或wb.save()中的文件名必须与output_filename参数一致。- 使用
execute_command执行 shell 任务 — 如ls、pip install、curl等。 - 使用
file_operations管理文件 — 明确读取、写入、列出和删除文件。 - 会话状态会保留 — 变量和文件会在多次调用之间保留。可将此功能用于多步工作流。
应避免的常见错误
- 忘记在
import matplotlib.pyplot as plt之前调用matplotlib.use('Agg') - 使用
plt.show()而不是plt.savefig()— 没有显示设备 output_filename中有拼写错误 — 必须与代码保存的文件名完全一致- 使用
execute_code执行 shell 任务 — 应改用execute_command - 通过
file_operations写入二进制文件 — 使用execute_code生成二进制文件,然后通过output_filename下载