Loading...
Loading...
Test and prototype code in a sandboxed environment. Use for debugging, verifying logic, or installing packages.
npx skill4agent add aws-samples/sample-strands-agent-with-agentcore code-interpreterpaths| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| string | Yes | Code to execute. Use | |
| string | No | | |
| string | No | | File to download after execution. Code must save a file with this exact name. Saved to workspace automatically. |
| Parameter | Type | Required | Description |
|---|---|---|---|
| string | Yes | Shell command to execute (e.g., |
| Parameter | Type | Required | Description |
|---|---|---|---|
| string | Yes | |
| list | For read/list/remove | File paths. read: |
| list | For write | Entries with |
{
"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"]
}| 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 | Check compatibility, test APIs |
| Debug code logic | code-interpreter | Isolate and test specific functions |
| Verify calculations | code-interpreter | Quick math or data checks |
| 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 | 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 |
code-interpreter/// 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": "..." }execute_codeworkspace_read("code-interpreter/chart.png")
workspace_read("code-interpreter/results.json")
workspace_list("code-interpreter/")Text files (,.py,.csv,.json, etc.) are transferred as-is. Binary files (.txt,.png,, etc.) are handled via base64 encoding automatically..xlsx
execute_commandfile_operationsrequestsurllibcurl| Library | Common Use |
|---|---|
| DataFrames, CSV/Excel I/O, groupby, pivot |
| Arrays, linear algebra, random, statistics |
| Line, bar, scatter, histogram, subplots |
| Interactive charts, 3D plots |
| Interactive visualization |
| Optimization, interpolation, signal processing |
| Regression, time series, hypothesis tests |
| Algebra, calculus, equation solving |
| Library | Common Use |
|---|---|
| Classification, regression, clustering, pipelines |
| Deep learning, computer vision, audio |
| High-performance gradient boosting |
| NLP, tokenization, NER, sentiment |
| Image processing, filters, segmentation |
| Library | Common Use |
|---|---|
| Convex optimization, portfolio optimization |
| Scheduling, routing, constraint programming |
| Linear programming |
| SAT solving, formal verification |
| Graph algorithms, network analysis |
| Library | Common Use |
|---|---|
| Excel read/write with formatting |
| Word document creation/modification |
| PowerPoint creation/modification |
| PDF read/write/generate |
| XML/HTML parsing |
| Convert various formats to Markdown |
| Library | Common Use |
|---|---|
| Image resize, crop, filter, conversion |
| Computer vision, feature detection |
| Image/video I/O and editing |
| Audio manipulation |
| SVG creation, ImageMagick |
| Library | Common Use |
|---|---|
| SQL queries on DataFrames and files |
| SQL ORM and database abstraction |
| Parquet and Arrow format processing |
| Fast JSON/YAML parsing |
| Library | Common Use |
|---|---|
| HTTP requests, API calls |
| Web scraping |
| Web frameworks |
| Library | Common Use |
|---|---|
| Data validation, schema definition |
| Test data generation |
| Pretty printing, tables |
| Encryption, hashing |
| QR code generation |
| 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 CSVdfmatplotlib.use('Agg')import matplotlib.pyplotprint()output_filenameplt.savefig()wb.save()output_filenameexecute_commandlspip installcurlfile_operationsmatplotlib.use('Agg')import matplotlib.pyplot as pltplt.show()plt.savefig()output_filenameexecute_codeexecute_commandfile_operationsexecute_codeoutput_filename