code-interpreter by aws-samples/sample-strands-agent-with-agentcore
npx skills add https://github.com/aws-samples/sample-strands-agent-with-agentcore --skill code-interpreter一个由 AWS Bedrock AgentCore 代码解释器驱动的通用代码执行环境。在安全的沙盒中运行代码、执行 shell 命令和管理文件。
paths 以保存沙盒根目录中的所有文件。| 参数 | 类型 | 必需 | 默认值 | 描述 |
|---|---|---|---|---|
code | string | 是 | 要执行的代码。使用 print() 进行文本输出。 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
language | string | 否 | "python" | "python"、"javascript" 或 "typescript" |
output_filename | string | 否 | "" | 执行后要下载的文件。代码必须保存一个与此名称完全相同的文件。会自动保存到工作区。 |
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
command | string | 是 | 要执行的 shell 命令(例如,"ls -la"、"pip install requests")。 |
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
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"}] |
{
"code": "import pandas as pd\ndf = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})\nprint(df.describe())",
"language": "python"
}
{
"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"
}
{
"command": "pip install yfinance"
}
{
"command": "python --version && pip list | head -20"
}
{
"operation": "write",
"content": [{"path": "config.json", "text": "{\"key\": \"value\"}"}]
}
{
"operation": "list",
"paths": ["."]
}
{
"operation": "read",
"paths": ["output.csv"]
}
将代码解释器用作测试和原型设计代码的沙盒。对于生产任务(创建文档、图表、演示文稿),请优先使用专门的技能。
请勿用于:
| 任务 | 推荐技能 | 备注 |
|---|---|---|
| 创建图表/图表 | visual-design | 生产图表优先使用此技能 |
| 创建 Word 文档 | word-documents | 支持模板和样式 |
| 创建 Excel 电子表格 | excel-spreadsheets | 具有格式化管道和验证功能 |
| 创建 PowerPoint | powerpoint-presentations | 具有布局系统和设计模式 |
| 测试代码片段 | code-interpreter | 调试、验证逻辑、检查输出 |
| 原型设计算法 | code-interpreter | 在实施前进行实验 |
| 安装/测试包 | code-interpreter | 检查兼容性、测试 API |
| 调试代码逻辑 | code-interpreter | 隔离并测试特定功能 |
| 验证计算 | code-interpreter | 快速数学或数据检查 |
| 代码解释器 | 代码代理
---|---|---
性质 | 沙盒化执行环境 | 自主代理(Claude Code)
最适合 | 快速脚本、数据分析、原型设计 | 多文件项目、重构、测试套件
文件持久性 | 仅在设置 output_filename 时 | 所有文件自动同步到 S3
会话状态 | 变量在会话内持续存在 | 文件和对话在会话间持续存在
自主性 | 您编写代码 | 代理规划、编写、运行和迭代
使用时机 | 您需要运行特定代码片段 | 您需要工程师端到端解决问题
所有文件都进入 code-interpreter/ 命名空间——这是一个扁平的、会话隔离的空间,与办公文档分开。
沙盒 → 工作区(保存输出):
// 执行后保存特定文件
{ "tool": "ci_push_to_workspace", "paths": ["chart.png", "results.json"] }
// 保存沙盒根目录中的所有内容
{ "tool": "ci_push_to_workspace" }
// 替代方案:在 execute_code 期间内联保存单个文件
{ "tool": "execute_code", "output_filename": "chart.png", "code": "..." }
上传的文件(自动预加载):
用户上传的文件(例如 ZIP 存档)会自动在沙盒中可用——无需手动加载。只需在 execute_code 中直接使用它们。
通过工作区技能读取已保存的文件:
workspace_read("code-interpreter/chart.png")
workspace_read("code-interpreter/results.json")
workspace_list("code-interpreter/")
文本文件(
.py、.csv、.json、.txt等)按原样传输。二进制文件(.png、.xlsx等)通过 base64 编码自动处理。
execute_command 完全访问 shellfile_operations 管理文件requests、urllib、curl)| 库 | 常见用途 |
|---|---|
pandas | 数据框、CSV/Excel I/O、分组、透视 |
numpy | 数组、线性代数、随机、统计 |
matplotlib | 折线图、条形图、散点图、直方图、子图 |
plotly | 交互式图表、3D 图 |
bokeh | 交互式可视化 |
scipy | 优化、插值、信号处理 |
statsmodels | 回归、时间序列、假设检验 |
sympy | 代数、微积分、方程求解 |
| 库 | 常见用途 |
|---|---|
scikit-learn | 分类、回归、聚类、管道 |
torch / torchvision / torchaudio | 深度学习、计算机视觉、音频 |
xgboost | 高性能梯度提升 |
spacy / nltk / textblob | 自然语言处理、分词、命名实体识别、情感分析 |
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 | 图像/视频 I/O 和编辑 |
pydub | 音频操作 |
svgwrite / Wand | SVG 创建、ImageMagick |
| 库 | 常见用途 |
|---|---|
duckdb | 对数据框和文件进行 SQL 查询 |
SQLAlchemy | SQL ORM 和数据库抽象 |
pyarrow | Parquet 和 Arrow 格式处理 |
orjson / ujson / PyYAML | 快速 JSON/YAML 解析 |
| 库 | 常见用途 |
|---|---|
requests / httpx | HTTP 请求、API 调用 |
beautifulsoup4 | 网络抓取 |
fastapi / Flask / Django | Web 框架 |
| 库 | 常见用途 |
|---|---|
pydantic | 数据验证、模式定义 |
Faker | 测试数据生成 |
rich | 美观打印、表格 |
cryptography | 加密、哈希 |
qrcode | 二维码生成 |
boto3 | AWS SDK |
要查看包含版本的 200+ 个库的完整列表,请运行:
execute_command(command="pip list")
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}%")
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')
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))
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))
import requests
import pandas as pd
response = requests.get("https://api.example.com/data")
data = response.json()
df = pd.DataFrame(data)
print(df.head())
调用 1: execute_code → 加载和清理数据,存储在变量 `df` 中
调用 2: execute_code → 分析 `df`,生成图表,保存为 PNG
调用 3: execute_code → 将结果导出到 CSV
调用 4: file_operations(operation="read") → 下载 CSV
变量(df)和文件在同一会话的多次调用中持续存在。
import matplotlib.pyplot 之前使用 matplotlib.use('Agg') — 沙盒没有显示界面。print() 进行文本输出 — 标准输出是返回结果的方式。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_commandfile_operations 写入二进制文件 — 使用 execute_code 生成二进制文件,然后使用 output_filename 下载每周安装数
29
代码仓库
GitHub 星标数
110
首次出现
9 天前
安全审计
安装于
codex28
cursor27
gemini-cli27
github-copilot27
amp27
cline27
A general-purpose code execution environment powered by AWS Bedrock AgentCore Code Interpreter. Run code, execute shell commands, and manage files in a secure sandbox.
paths to save all files in the sandbox root.| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
code | string | Yes | Code to execute. Use print() for text output. | |
language | string | No | "python" | "python", "javascript", or "typescript" |
output_filename | string | No | "" | File to download after execution. Code must save a file with this exact name. Saved to workspace automatically. |
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Shell command to execute (e.g., "ls -la", "pip install requests"). |
| Parameter | Type | Required | Description |
|---|---|---|---|
operation | string | Yes | "read", "write", "list", or "remove" |
paths | list | For read/list/remove | File paths. read: ["file.txt"], list: , remove: |
{
"code": "import pandas as pd\ndf = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})\nprint(df.describe())",
"language": "python"
}
{
"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"
}
{
"command": "pip install yfinance"
}
{
"command": "python --version && pip list | head -20"
}
{
"operation": "write",
"content": [{"path": "config.json", "text": "{\"key\": \"value\"}"}]
}
{
"operation": "list",
"paths": ["."]
}
{
"operation": "read",
"paths": ["output.csv"]
}
Use code-interpreter as a sandbox for testing and prototyping code. For production tasks (creating documents, charts, presentations), prefer specialized skills.
Do NOT use for:
| Task | Recommended Skill | Notes |
|---|---|---|
| Create charts/diagrams | visual-design | Use this first for production charts |
| Create Word documents | word-documents | Has template support and styling |
| Create Excel spreadsheets | excel-spreadsheets | Has formatting pipeline and validation |
| Create PowerPoint | powerpoint-presentations | Has layout system and design patterns |
| Test code snippets | code-interpreter | Debug, verify logic, check output |
| Prototype algorithms | code-interpreter | Experiment before implementing |
| Install/test packages |
| Code Interpreter | Code Agent
---|---|---
Nature | Sandboxed execution environment | Autonomous agent (Claude Code)
Best for | Quick scripts, data analysis, prototyping | Multi-file projects, refactoring, test suites
File persistence | Only when output_filename is set | All files auto-synced to S3
Session state | Variables persist within session | Files + conversation persist across sessions
Autonomy | You write the code | Agent plans, writes, runs, and iterates
Use when | You need to run a specific piece of code | You need an engineer to solve a problem end-to-end
All files go to the code-interpreter/ namespace — a flat, session-isolated space separate from office documents.
Sandbox → Workspace (save outputs):
// Save a specific file after execution
{ "tool": "ci_push_to_workspace", "paths": ["chart.png", "results.json"] }
// Save everything in the sandbox root
{ "tool": "ci_push_to_workspace" }
// Alternative: save a single file inline during execute_code
{ "tool": "execute_code", "output_filename": "chart.png", "code": "..." }
Uploaded files (auto-preloaded):
Files uploaded by the user (e.g. ZIP archives) are automatically available in the sandbox — no manual loading needed. Just use them directly in execute_code.
Read saved files via workspace skill:
workspace_read("code-interpreter/chart.png")
workspace_read("code-interpreter/results.json")
workspace_list("code-interpreter/")
Text files (
.py,.csv,.json,.txt, etc.) are transferred as-is. Binary files (.png,.xlsx, etc.) are handled via base64 encoding automatically.
execute_commandfile_operations to manage filesrequests, urllib, curl)| Library | Common Use |
|---|---|
pandas | DataFrames, CSV/Excel I/O, groupby, pivot |
numpy | Arrays, linear algebra, random, statistics |
matplotlib | Line, bar, scatter, histogram, subplots |
plotly | Interactive charts, 3D plots |
bokeh | Interactive visualization |
scipy | Optimization, interpolation, signal processing |
| Library | Common Use |
|---|---|
scikit-learn | Classification, regression, clustering, pipelines |
torch / torchvision / torchaudio | Deep learning, computer vision, audio |
xgboost | High-performance gradient boosting |
spacy / nltk / textblob |
| Library | Common Use |
|---|---|
cvxpy | Convex optimization, portfolio optimization |
ortools | Scheduling, routing, constraint programming |
pulp | Linear programming |
z3-solver | SAT solving, formal verification |
networkx / igraph | Graph algorithms, network analysis |
| Library | Common Use |
|---|---|
openpyxl / xlrd / XlsxWriter | Excel read/write with formatting |
python-docx | Word document creation/modification |
python-pptx | PowerPoint creation/modification |
PyPDF2 / pdfplumber / reportlab |
| Library | Common Use |
|---|---|
pillow (PIL) | Image resize, crop, filter, conversion |
opencv-python (cv2) | Computer vision, feature detection |
imageio / moviepy | Image/video I/O and editing |
pydub | Audio manipulation |
svgwrite / Wand |
| Library | Common Use |
|---|---|
duckdb | SQL queries on DataFrames and files |
SQLAlchemy | SQL ORM and database abstraction |
pyarrow | Parquet and Arrow format processing |
orjson / ujson / PyYAML | Fast JSON/YAML parsing |
| Library | Common Use |
|---|---|
requests / httpx | HTTP requests, API calls |
beautifulsoup4 | Web scraping |
fastapi / Flask / Django | Web frameworks |
| Library | Common Use |
|---|---|
pydantic | Data validation, schema definition |
Faker | Test data generation |
rich | Pretty printing, tables |
cryptography | Encryption, hashing |
qrcode | QR code generation |
boto3 | AWS SDK |
For the full list of 200+ libraries with versions, run:
execute_command(command="pip list")
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}%")
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')
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))
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))
import requests
import pandas as pd
response = requests.get("https://api.example.com/data")
data = response.json()
df = pd.DataFrame(data)
print(df.head())
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
Variables (df) and files persist across calls in the same session.
matplotlib.use('Agg') before import matplotlib.pyplot — sandbox has no display.print() for text output — stdout is how results are returned.output_filename must match exactly — the filename in plt.savefig() or wb.save() must match the output_filename parameter.execute_command for shell tasks — ls, pip install, , etc.matplotlib.use('Agg') before import matplotlib.pyplot as pltplt.show() instead of plt.savefig() — there is no displayoutput_filename — must match the file saved by the code exactlyexecute_code for shell tasks — use execute_command insteadfile_operations — use execute_code to generate binary files, then download with output_filenameWeekly Installs
29
Repository
GitHub Stars
110
First Seen
9 days ago
Security Audits
Gen Agent Trust HubWarnSocketPassSnykWarn
Installed on
codex28
cursor27
gemini-cli27
github-copilot27
amp27
cline27
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
118,000 周安装
["."]["old.txt"]content | list | For write | Entries with path and text: [{"path": "out.txt", "text": "hello"}] |
| Check compatibility, test APIs |
| Debug code logic | code-interpreter | Isolate and test specific functions |
| Verify calculations | code-interpreter | Quick math or data checks |
statsmodels | Regression, time series, hypothesis tests |
sympy | Algebra, calculus, equation solving |
| NLP, tokenization, NER, sentiment |
scikit-image | Image processing, filters, segmentation |
| PDF read/write/generate |
lxml / beautifulsoup4 | XML/HTML parsing |
markitdown | Convert various formats to Markdown |
| SVG creation, ImageMagick |
curlfile_operations for file management — read/write/list/remove files explicitly.